지금까지 문자열을 간단히 사용해왔지만, 파이썬에서 문자열을 만드는 방법은 생각보다 다양합니다. 작은따옴표만 사용해야 하는 것도 아니고, 한 줄에만 작성해야 하는 것도 아닙니다. 이번 포스트에서는 파이썬에서 문자열을 만드는 다양한 방법과 각 방법이 필요한 상황을 알아보겠습니다.
파이썬에서 문자열을 만드는 가장 기본적인 방법은 따옴표로 감싸는 것입니다.
message = 'Hello, Python!'
print(message) # Hello, Python!
message = "Hello, Python!"
print(message) # Hello, Python!
작은따옴표와 큰따옴표는 기능적으로 완전히 동일합니다. 어떤 것을 사용해도 상관없으며, 일관성 있게 사용하는 것이 중요합니다.
# 둘 다 동일한 결과
text1 = 'Python'
text2 = "Python"
print(text1 == text2) # True
문자열 안에 따옴표를 넣어야 하는 경우가 종종 있습니다. 이때 다른 종류의 따옴표를 사용하거나 이스케이프 문자를 사용합니다.
문자열을 큰따옴표로 감싸면 내부에 작은따옴표를 자유롭게 사용할 수 있고, 그 반대도 가능합니다.
# 문자열 안에 작은따옴표 포함
message1 = "It's a beautiful day!"
print(message1) # It's a beautiful day!
# 문자열 안에 큰따옴표 포함
message2 = 'He said "Hello!"'
print(message2) # He said "Hello!"
이 방법이 가장 간단하고 읽기 쉽습니다.
같은 종류의 따옴표를 사용해야 한다면 백슬래시(\)로 이스케이프합니다.
# 작은따옴표 문자열 안에 작은따옴표
message1 = 'It\'s a beautiful day!'
print(message1) # It's a beautiful day!
# 큰따옴표 문자열 안에 큰따옴표
message2 = "He said \"Hello!\""
print(message2) # He said "Hello!"
# HTML 코드를 문자열로 저장
html1 = '<a href="https://python.org">Python</a>'
print(html1)
# 또는 이스케이프 사용
html2 = "<a href=\"https://python.org\">Python</a>"
print(html2)
# 둘 다 동일한 결과
print(html1 == html2) # True
일반적인 따옴표로는 한 줄만 작성할 수 있습니다.
# 에러 발생!
text = 'This is
a multiline
string' # SyntaxError
제어 문자 \n을 사용하여 줄바꿈을 표현할 수 있습니다.
text = 'This is\na multiline\nstring'
print(text)
출력 결과:
This is
a multiline
string
하지만 긴 문자열의 경우 가독성이 떨어집니다.
작은따옴표 3개(''') 또는 큰따옴표 3개(""") 를 사용하면 여러 줄로 된 문자열을 자연스럽게 작성할 수 있습니다.
text = '''This is
a multiline
string'''
print(text)
출력 결과:
This is
a multiline
string
text = """This is
a multiline
string"""
print(text)
출력 결과:
This is
a multiline
string
message = '''He said "It's a beautiful day!"
I replied, 'Yes, it is!'
We both smiled.'''
print(message)
출력 결과:
He said "It's a beautiful day!"
I replied, 'Yes, it is!'
We both smiled.
query = """
SELECT name, age, city
FROM users
WHERE age >= 18
ORDER BY name
"""
print(query)
출력 결과:
SELECT name, age, city
FROM users
WHERE age >= 18
ORDER BY name
email = """
안녕하세요, {name}님!
주문하신 상품이 발송되었습니다.
배송 예정일: {date}
감사합니다.
"""
print(email)
html = """
<div class="container">
<h1>Welcome to Python</h1>
<p>This is a "great" language!</p>
</div>
"""
print(html)
파이썬에서는 함수나 클래스의 설명을 작성할 때 삼중 따옴표를 사용합니다.
def calculate_area(width, height):
"""
사각형의 넓이를 계산합니다.
Args:
width: 사각형의 가로 길이
height: 사각형의 세로 길이
Returns:
사각형의 넓이
"""
return width * height
print(calculate_area.__doc__) # 문서화 문자열 출력
삼중 따옴표를 사용할 때 들여쓰기가 그대로 포함됩니다.
def print_message():
message = """
Hello
World
"""
print(message)
print_message()
출력 결과 (들여쓰기 포함):
Hello
World
from textwrap import dedent
def print_message():
message = dedent("""
Hello
World
""")
print(message)
print_message()
출력 결과 (들여쓰기 제거):
Hello
World
message = """Hello
World
Python"""
print(message)
출력 결과:
Hello
World
Python
first = "Hello"
second = "World"
result = first + " " + second
print(result) # Hello World
# 괄호 안에서 자동 연결
message = (
"This is a very long string that "
"spans multiple lines for better "
"readability in the code."
)
print(message)
# This is a very long string that spans multiple lines for better readability in the code.
message = "This is a very long string that " \
"spans multiple lines for better " \
"readability in the code."
print(message)
빈 문자열은 길이가 0인 문자열입니다.
empty1 = ''
empty2 = ""
empty3 = ''''''
print(len(empty1)) # 0
print(len(empty2)) # 0
print(len(empty3)) # 0
print(empty1 == empty2 == empty3) # True
문자열과 숫자는 서로 다른 자료형이므로 직접 연결할 수 없습니다.
# 에러 발생!
age = 25
message = "I am " + age + " years old" # TypeError
age = 25
message = "I am " + str(age) + " years old"
print(message) # I am 25 years old
age = 25
message = f"I am {age} years old"
print(message) # I am 25 years old
* 연산자로 문자열을 반복할 수 있습니다.
print("=" * 30)
# ==============================
print("Python! " * 3)
# Python! Python! Python!
# 구분선 만들기
print("-" * 50)
# 대소문자 구분
print("python" == "Python") # False
print("python" == "python") # True
# 사전 순서 비교
print("apple" < "banana") # True
print("Apple" < "apple") # True (대문자가 먼저)