문자열 사용하기

Tasker_Jang·2026년 2월 1일

들어가며

지금까지 문자열을 간단히 사용해왔지만, 파이썬에서 문자열을 만드는 방법은 생각보다 다양합니다. 작은따옴표만 사용해야 하는 것도 아니고, 한 줄에만 작성해야 하는 것도 아닙니다. 이번 포스트에서는 파이썬에서 문자열을 만드는 다양한 방법과 각 방법이 필요한 상황을 알아보겠습니다.

문자열 만드는 기본 방법

파이썬에서 문자열을 만드는 가장 기본적인 방법은 따옴표로 감싸는 것입니다.

1. 작은따옴표 (Single Quotes)

message = 'Hello, Python!'
print(message)  # Hello, Python!

2. 큰따옴표 (Double Quotes)

message = "Hello, Python!"
print(message)  # Hello, Python!

작은따옴표와 큰따옴표는 기능적으로 완전히 동일합니다. 어떤 것을 사용해도 상관없으며, 일관성 있게 사용하는 것이 중요합니다.

# 둘 다 동일한 결과
text1 = 'Python'
text2 = "Python"

print(text1 == text2)  # True

문자열 안에 따옴표 포함하기

문자열 안에 따옴표를 넣어야 하는 경우가 종종 있습니다. 이때 다른 종류의 따옴표를 사용하거나 이스케이프 문자를 사용합니다.

방법 1: 다른 종류의 따옴표 사용

문자열을 큰따옴표로 감싸면 내부에 작은따옴표를 자유롭게 사용할 수 있고, 그 반대도 가능합니다.

# 문자열 안에 작은따옴표 포함
message1 = "It's a beautiful day!"
print(message1)  # It's a beautiful day!

# 문자열 안에 큰따옴표 포함
message2 = 'He said "Hello!"'
print(message2)  # He said "Hello!"

이 방법이 가장 간단하고 읽기 쉽습니다.

방법 2: 이스케이프 문자 사용

같은 종류의 따옴표를 사용해야 한다면 백슬래시(\)로 이스케이프합니다.

# 작은따옴표 문자열 안에 작은따옴표
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

해결 방법 1: \n 사용

제어 문자 \n을 사용하여 줄바꿈을 표현할 수 있습니다.

text = 'This is\na multiline\nstring'
print(text)

출력 결과:

This is
a multiline
string

하지만 긴 문자열의 경우 가독성이 떨어집니다.

해결 방법 2: 삼중 따옴표 사용 (권장)

작은따옴표 3개(''') 또는 큰따옴표 3개(""") 를 사용하면 여러 줄로 된 문자열을 자연스럽게 작성할 수 있습니다.

작은따옴표 3개

text = '''This is
a multiline
string'''

print(text)

출력 결과:

This is
a multiline
string

큰따옴표 3개

text = """This is
a multiline
string"""

print(text)

출력 결과:

This is
a multiline
string

삼중 따옴표의 장점

  1. 자연스러운 줄바꿈: 코드에서 보이는 대로 출력됩니다
  2. 따옴표 자유롭게 사용: 내부에 작은따옴표, 큰따옴표 모두 사용 가능
  3. 가독성: 긴 텍스트를 작성할 때 매우 편리
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.

삼중 따옴표 실용 예시

1. SQL 쿼리 작성

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

2. 이메일 템플릿

email = """
안녕하세요, {name}님!

주문하신 상품이 발송되었습니다.
배송 예정일: {date}

감사합니다.
"""

print(email)

3. HTML 코드

html = """
<div class="container">
    <h1>Welcome to Python</h1>
    <p>This is a "great" language!</p>
</div>
"""

print(html)

4. 문서화 문자열 (Docstring)

파이썬에서는 함수나 클래스의 설명을 작성할 때 삼중 따옴표를 사용합니다.

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
    

해결 방법 1: textwrap.dedent() 사용

from textwrap import dedent

def print_message():
    message = dedent("""
        Hello
        World
    """)
    print(message)

print_message()

출력 결과 (들여쓰기 제거):


Hello
World

해결 방법 2: 첫 줄을 따옴표와 같은 줄에 시작

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

해결 방법 1: str() 함수로 변환

age = 25
message = "I am " + str(age) + " years old"
print(message)  # I am 25 years old

해결 방법 2: f-string 사용 (권장)

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 (대문자가 먼저)
profile
ML Engineer 🧠 | AI 모델 개발과 최적화 경험을 기록하며 성장하는 개발자 🚀 The light that burns twice as bright burns half as long ✨

0개의 댓글