[Python] String concatenation

Yerin·2019년 11월 27일
0

study-python

목록 보기
3/18

숫자처럼 string도 더할 수 있다. 이를 'string concatentation'이라고 한다. 두개 혹은 그 이상의 문자열을 이을 수 있다.

print("Hello, World")
print("Hello," + "World")

string concatenation 은 특정 문자열만 변수에 저장되어있을때 사용하면 편하다. 예를 들어, input으로 받은 유저의 이름을 저장한 변수를 사용해서 출력하고 싶을 경우에는 사용하면 편리하다.

name = input()
print("Hello," + name)

만일 "meekukin"이란 값이 input으로 입력됐으면 , "Hello, meekukin" 이라고 출력된다.

  • 복잡한 string concatenation
    • 이외에도, 길고 복잡한 문자열인 경우에는 다른 효과적인 방법이 있다.
      그 중에 하나가 literal string interpolation 이다.

      name = input()
      print(f"Hello, {name}")

      이 방법을 사용하려면 아래의 문법을 지켜야 한다.

    1. 먼저 따옴표 앞에 "f"를 붙여야 한다. f 다음에 오는 string값을 literal strinng interpolation이라고 인지하고 스트링 안에 있는 변수들을 실제 값으로 치환한다.
    2. 치환하고 싶은 변수, 혹은 함수 호출 등을 중괄호를 사용해서 표시한다.
  • Multiline f-strings
  • Multiline f-Strings
    You can have multiline strings:

>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
...     f"Hi {name}. "
...     f"You are a {profession}. "
...     f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'
But remember that you need to place an f in front of each line of a multiline string. The following code won’t work:

>>> message = (
...     f"Hi {name}. "
...     "You are a {profession}. "
...     "You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a {profession}. You were in {affiliation}.'

If you don’t put an f in front of each individual line, then you’ll just have regular, old, garden-variety strings and not shiny, new, fancy f-strings.

If you want to spread strings over multiple lines, you also have the option of escaping a return with a \:

>>> message = f"Hi {name}. " \
...           f"You are a {profession}. " \
...           f"You were in {affiliation}."
...
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'
But this is what will happen if you use """:

>>> message = f"""
...     Hi {name}. 
...     You are a {profession}. 
...     You were in {affiliation}.
... """
...
>>> message
'\n    Hi Eric.\n    You are a comedian.\n    You were in Monty Python.\n
ref:
https://realpython.com/python-f-strings/
profile
졸꾸 !!!

0개의 댓글