[TIL] Python Concatenating Text Strings

Hailee·2020년 11월 19일
0

[ TIL ]

목록 보기
7/40
post-thumbnail

String Concatenation

  • String Concatenation
    : 숫자를 더하듯이, 문자열도 더하기 가능!
    : 특정 문자열만 변수에 저장된 경우 사용이 더 편리
    : + 연산자 사용
print("Hello, World")
print("Hello, " + "World")

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

이런 식으로 input으로 입력받은 값을 저장한 변수를 사용하서 출력하는 경우
String Concatenation 사용하면 편리하다


복잡한 String Concatenation

  • Literal String Interpolation
    : 길고 복잡한 문자열의 경우 훨씬 편리!
    : f""" 사용
date            = 1980
python_inventor = "Guido van Rossum"
location        = "Centrum Wiskunde & Informatica"
country         = "Netherlands"


print(f"""Python was conceived in the late {date}s 
by {python_inventor} at {location} (CWI) in the {country} as a successor 
to the ABC language (itself inspired by SETL), capable of exception handling 
and interfacing with the Amoeba operating system. 
Its implementation began in December 1989.""")

literal string concatenation

  1. 따옴표 앞에 "f"를 붙여주면,
  2. f""" 다음의 String 값을 literal string interpolation 이라고 인지하고,
  3. 변수들을 실제 값으로 치환한다.

문자열 text가 길고 복잡한 경우, +를 사용해서 문자열을 합치는 것 보다
literal string interpolation을 사용하는게 훨씬 편리하다!!

Python's f-Strings 참고


텍스트 치환하기

위의 예제처럼 치환하고 싶은 변수를 중괄호{ } 로 표시해도 되지만,

new_gee = input("Gee 를 입력해주세요: ") 

gee = f"""
너무 너무 멋져 눈이 눈이 부셔
숨을 못 쉬겠어 떨리는 Girl
Gee Gee Gee Gee
Baby Baby Baby Baby
Gee Gee Gee Gee
Baby Baby Baby Baby
"""

print(gee.replace("Gee", new_gee))

이렇게 치환 메서드를 사용하면 훨씬 효율적이다!

'Gee'라는 단어를 하나하나 중괄호로 감싸고 바꾸는 과정보다
전체 문자열 text를 하나의 변수로 두고 replace 메서드를 사용하면 된다!
파이썬 문자열 다루기!

profile
웹 개발 🐷😎👊🏻🔥

0개의 댓글