Python & AI Tutorials Logo
Python 프로그래밍

6. 실전 문자열 처리

5장에서 문자열을 다루는 기초를 배웠습니다. 문자열을 생성하고, 인덱싱과 슬라이싱으로 문자에 접근하고, 기본적인 문자열 메서드를 사용하는 방법이었습니다. 이제 그 기초 위에, 실제 Python 프로그램에서 끊임없이 사용하게 될 좀 더 정교한 문자열 연산을 살펴보겠습니다.

이 장에서는 텍스트를 분해했다가 다시 합치고, 전문적으로 보이는 형식화된 출력(formatted output)을 만드는 등, 일상적인 프로그래밍 문제를 해결하는 실용적인 문자열 조작 기법에 초점을 맞춥니다. 이런 기술은 사용자 입력을 처리하거나, 보고서를 생성하거나, 데이터 파일을 읽거나, 텍스트를 다루는 모든 프로그램을 만들 때 필수적입니다.

6.1) 문자열 분할과 결합

텍스트 처리에서 가장 흔한 작업 중 하나는 문자열을 더 작은 조각으로 나누거나 여러 조각을 하나의 문자열로 결합하는 일입니다. Python은 두 작업 모두를 위한 강력한 메서드를 제공합니다.

6.1.1) split()으로 문자열 나누기

split() 메서드는 구분자(separator, delimiter라고도 부릅니다)를 기준으로 문자열을 더 작은 문자열들의 리스트로 나눕니다. CSV 데이터처럼 구조화된 텍스트, 여러 값을 포함한 사용자 입력, 문장을 단어로 나누는 작업 등에 매우 유용합니다.

기본 공백 기준 분할:

split()을 인수 없이 호출하면, 공백 문자(스페이스, 탭, 개행)를 기준으로 분할하고, 결과에서 빈 문자열은 자동으로 제거합니다:

python
# split_basic.py
sentence = "Python is a powerful programming language"
words = sentence.split()
print(words)  # Output: ['Python', 'is', 'a', 'powerful', 'programming', 'language']
print(len(words))  # Output: 6

split()이 여러 개의 공백을 어떻게 똑똑하게 처리하는지 살펴보세요:

python
# split_whitespace.py
messy_text = "Python    is     awesome"
words = messy_text.split()
print(words)  # Output: ['Python', 'is', 'awesome']

단어 사이에 공백이 여러 개 있어도, split()은 어떤 양의 공백이든 하나의 구분자로 취급하고 깔끔한 리스트를 만들어 줍니다.

특정 구분자로 분할하기:

인수로 어떤 문자나 문자열을 넘겨서, 무엇을 기준으로 나눌지 정확히 지정할 수 있습니다:

python
# split_separator.py
csv_data = "apple,banana,cherry,date"
fruits = csv_data.split(',')
print(fruits)  # Output: ['apple', 'banana', 'cherry', 'date']
 
date_string = "2024-03-15"
parts = date_string.split('-')
print(parts)  # Output: ['2024', '03', '15']
year = parts[0]
month = parts[1]
day = parts[2]
print(f"Year: {year}, Month: {month}, Day: {day}")  # Output: Year: 2024, Month: 03, Day: 15

중요한 차이점: 구분자를 명시하면, split()은 그 구분자를 문자 그대로 처리하며, 구분자가 연속해서 나타날 경우 빈 문자열을 생성합니다:

python
# split_empty_strings.py
data = "apple,,cherry"
result = data.split(',')
print(result)  # Output: ['apple', '', 'cherry']
print(len(result))  # Output: 3

가운데의 빈 문자열 ''은 두 개의 연속된 콤마 사이의 "아무것도 없음"을 나타냅니다. 이 동작은 인수 없이 공백 기준으로 분할할 때와는 다릅니다.

분할 횟수 제한하기:

두 번째 인수(maxsplit)를 넘겨서, 몇 번까지 분할할지 제어할 수 있습니다:

python
# split_maxsplit.py
text = "one:two:three:four:five"
parts = text.split(':', 2)  # 처음 2개의 콜론에서만 분할
print(parts)  # Output: ['one', 'two', 'three:four:five']

이는 최대 3개의 조각(maxsplit + 1)을 만듭니다. 지정한 분할 횟수에 도달하면 더 이상 나누지 않고, 나머지 문자열은 그대로 둡니다.

실용 예제: 사용자 입력 처리

python
# process_input.py
user_input = input("Enter your full name: ")
# 사용자가 입력: "Alice Marie Johnson"
 
name_parts = user_input.split()
if len(name_parts) >= 2:
    first_name = name_parts[0]
    last_name = name_parts[-1]  # 마지막 요소
    print(f"First name: {first_name}")  # Output: First name: Alice
    print(f"Last name: {last_name}")    # Output: Last name: Johnson
else:
    print("Please enter at least a first and last name")

6.1.2) join()으로 문자열 결합하기

join() 메서드는 split()의 반대입니다. 문자열들의 리스트(또는 어떤 iterable이든)를 하나의 문자열로 결합하면서, 각 요소 사이에 구분자 문자열을 넣습니다. 문법이 처음에는 조금 뒤바뀐 것처럼 보일 수 있는데, 구분자 문자열이 메서드를 호출하고, 리스트를 인수로 넘깁니다.

기본 결합:

python
# join_basic.py
words = ['Python', 'is', 'awesome']
sentence = ' '.join(words)
print(sentence)  # Output: Python is awesome
 
csv_line = ','.join(['apple', 'banana', 'cherry'])
print(csv_line)  # Output: apple,banana,cherry

' ', ','처럼 join()을 호출한 문자열이 각 요소 사이의 구분자가 됩니다.

왜 문법이 separator.join(list)일까:

이 문법은 구분자의 관점에서 생각하면 이해가 됩니다. "이 항목들을 서로 이어 붙이되, 각 쌍 사이에 나 자신을 끼워 넣고 싶다." 또한 이 방식 덕분에 체이닝이 자연스럽고, 코드에서 구분자가 매우 눈에 잘 띕니다.

다양한 구분자로 결합하기:

python
# join_separators.py
items = ['eggs', 'milk', 'bread', 'butter']
 
# 콤마로 구분
print(', '.join(items))  # Output: eggs, milk, bread, butter
 
# 줄바꿈으로 구분 (각 항목을 한 줄씩)
print('\n'.join(items))
# Output:
# eggs
# milk
# bread
# butter
 
# 하이픈으로 구분
print('-'.join(items))  # Output: eggs-milk-bread-butter
 
# 구분자 없이(단순 이어 붙이기)
print(''.join(items))  # Output: eggsmilkbreadbutter

중요: join()은 문자열에만 동작합니다:

iterable의 모든 요소가 문자열이어야 합니다. 숫자나 다른 타입을 결합하려 하면 에러가 발생합니다:

python
# join_error.py
numbers = [1, 2, 3, 4]
# result = ','.join(numbers)  # This would cause: TypeError: sequence item 0: expected str instance, int found

문자열이 아닌 항목을 결합하려면 먼저 문자열로 변환해야 합니다. 34장에서 이를 더 우아하게 처리하는 방법을 배우겠지만, 지금은 각 항목을 수동으로 변환해도 됩니다:

python
# join_numbers.py
numbers = [1, 2, 3, 4]
# 각 숫자를 수동으로 문자열로 변환
string_numbers = [str(numbers[0]), str(numbers[1]), str(numbers[2]), str(numbers[3])]
result = ','.join(string_numbers)
print(result)  # Output: 1,2,3,4

실용 예제: 파일 경로 만들기

python
# build_path.py
path_parts = ['home', 'user', 'documents', 'report.txt']
# 유닉스 계열 시스템(Linux, macOS)에서
unix_path = '/'.join(path_parts)
print(unix_path)  # Output: home/user/documents/report.txt
 
# Windows에서
windows_path = '\\'.join(path_parts)
print(windows_path)  # Output: home\user\documents\report.txt

참고: 26장에서 더 나은 크로스 플랫폼 경로 처리를 제공하는 os.path 모듈을 배울 것입니다. 여기서는 join 개념을 설명하기 위한 예제입니다.

6.1.3) split()과 join()을 조합한 텍스트 처리

이 두 메서드는 텍스트 변환에 함께 사용하면 특히 강력합니다. 조합해서 사용하면 지저분한 입력을 정리하고, 포맷을 변환하고, 데이터를 추출하거나 재구성할 수 있습니다:

python
# transform_text.py
# 여러 개의 공백을 하나의 공백으로 대체
messy = "Python    is     really    cool"
clean = ' '.join(messy.split())
print(clean)  # Output: Python is really cool
 
# 콤마로 구분된 데이터를 공백으로 구분된 형태로 변환
csv_data = "apple,banana,cherry"
space_separated = ' '.join(csv_data.split(','))
print(space_separated)  # Output: apple banana cherry
 
# 모든 공백 제거
text_with_spaces = "H e l l o"
no_spaces = ''.join(text_with_spaces.split())
print(no_spaces)  # Output: Hello

6.1.4) 다른 분할 메서드들

Python은 특정 용도에 맞는 추가적인 분할 메서드도 제공합니다.

rsplit() - 오른쪽부터 분할:

python
# rsplit_example.py
path = "folder/subfolder/file.txt"
 
# 일반 split과 maxsplit
parts = path.split('/', 1)
print(parts)  # Output: ['folder', 'subfolder/file.txt']
 
# rsplit은 오른쪽부터 분할
parts = path.rsplit('/', 1)
print(parts)  # Output: ['folder/subfolder', 'file.txt']

이는 문자열의 마지막 부분을 그 이전의 모든 부분과 분리하고 싶을 때 유용합니다.

splitlines() - 줄 나누기:

python
# splitlines_example.py
multiline = "Line 1\nLine 2\nLine 3"
lines = multiline.splitlines()
print(lines)  # Output: ['Line 1', 'Line 2', 'Line 3']
 
# 서로 다른 줄바꿈 스타일도 처리
mixed_lines = "Line 1\nLine 2\r\nLine 3\rLine 4"
all_lines = mixed_lines.splitlines()
print(all_lines)  # Output: ['Line 1', 'Line 2', 'Line 3', 'Line 4']

splitlines() 메서드는 모든 표준 줄 바꿈 표기(\n, \r\n, \r)를 인식해서 그에 따라 분할합니다. 따라서 서로 다른 소스에서 온 텍스트를 처리할 때 split('\n')보다 더 견고합니다.

6.2) f-string으로 문자열 포맷팅하기

형식화된 출력을 만드는 일은 프로그래밍에서 가장 흔한 작업 중 하나입니다. 텍스트에 변수 값을 섞어서 출력하고, 열을 정렬하고, 숫자를 포맷하고, 사용자에게 읽기 쉬운 출력을 만들어야 합니다. Python의 f-string(formatted string literal)은 이를 위한 가장 현대적이고, 가독성이 좋고, 강력한 방법입니다.

6.2.1) f-string의 기본 문법

f-string은 f 또는 F 접두사가 붙은 문자열 리터럴로, 중괄호 {} 안에 표현식을 포함할 수 있습니다. Python은 이 표현식을 평가하고 그 결과를 문자열로 변환합니다:

python
# fstring_basic.py
name = "Alice"
age = 30
greeting = f"Hello, {name}! You are {age} years old."
print(greeting)  # Output: Hello, Alice! You are 30 years old.

중괄호 {} 안의 표현식은 어떤 유효한 Python 표현식이든 될 수 있습니다:

python
# fstring_expressions.py
x = 10
y = 20
result = f"The sum of {x} and {y} is {x + y}"
print(result)  # Output: The sum of 10 and 20 is 30
 
price = 19.99
quantity = 3
total = f"Total cost: ${price * quantity}"
print(total)  # Output: Total cost: $59.97

6.2.2) f-string이 예전 방식보다 나은 이유

f-string이 도입되기 전(Python 3.6 이전)에는, 프로그래머들은 문자열 연결(concatenation)이나 format() 메서드를 사용했습니다. 비교해 보겠습니다.

문자열 연결(예전의, 오류가 나기 쉬운 방식):

python
# concatenation_example.py
name = "Bob"
age = 25
# 숫자를 문자열로 변환해야 하고, + 연산자가 많이 필요합니다
message = "Hello, " + name + "! You are " + str(age) + " years old."
print(message)  # Output: Hello, Bob! You are 25 years old.

이 방식은 장황하고, str() 호출을 빼먹기 쉽고(그러면 에러가 납니다), 변수 수가 많아지면 읽기 어렵습니다.

f-string(현대적이고 깔끔한 방식):

python
# fstring_clean.py
name = "Bob"
age = 25
message = f"Hello, {name}! You are {age} years old."
print(message)  # Output: Hello, Bob! You are 25 years old.

f-string은 값을 자동으로 문자열로 변환해 주고, 더 읽기 쉬우며, 실제로 다른 방식보다 더 빠르기도 합니다.

6.2.3) f-string 안에서의 표현식과 메서드 호출

f-string 안에는 복잡한 표현식, 메서드 호출, 함수 호출까지 넣을 수 있습니다:

python
# fstring_methods.py
name = "alice"
print(f"Capitalized: {name.capitalize()}")  # Output: Capitalized: Alice
print(f"Uppercase: {name.upper()}")  # Output: Uppercase: ALICE
print(f"Length: {len(name)}")  # Output: Length: 5
 
# 산술 연산과 비교
x = 10
print(f"Is {x} even? {x % 2 == 0}")  # Output: Is 10 even? True
 
# 인덱싱과 슬라이싱
text = "Python"
print(f"First letter: {text[0]}")  # Output: First letter: P
print(f"First three: {text[:3]}")  # Output: First three: Pyt

6.2.4) f-string에서 숫자 포맷팅하기

f-string은 값이 어떻게 표시될지 제어하는 포맷 지정자(format specifier)를 지원합니다. 문법은 {expression:format_spec}입니다.

부동소수점의 소수 자릿수 제어:

python
# fstring_decimals.py
pi = 3.14159265359
 
print(f"Default: {pi}")  # Output: Default: 3.14159265359
print(f"2 decimals: {pi:.2f}")  # Output: 2 decimals: 3.14
print(f"4 decimals: {pi:.4f}")  # Output: 4 decimals: 3.1416
print(f"No decimals: {pi:.0f}")  # Output: No decimals: 3

.2f라는 포맷 지정자는 "소수점 이하 2자리의 float로 표시하라"는 뜻입니다. f는 "fixed-point notation"을 의미합니다.

천 단위 구분 기호 넣기:

python
# fstring_thousands.py
large_number = 1234567890
 
print(f"No separator: {large_number}")  # Output: No separator: 1234567890
print(f"With commas: {large_number:,}")  # Output: With commas: 1,234,567,890
print(f"With underscores: {large_number:_}")  # Output: With underscores: 1_234_567_890
 
# 소수 자릿수와 함께 사용
price = 1234567.89
print(f"Price: ${price:,.2f}")  # Output: Price: $1,234,567.89

퍼센트 포맷팅:

python
# fstring_percentage.py
ratio = 0.847
print(f"Ratio: {ratio}")  # Output: Ratio: 0.847
print(f"Percentage: {ratio:.1%}")  # Output: Percentage: 84.7%
print(f"Percentage: {ratio:.2%}")  # Output: Percentage: 84.70%

% 포맷 지정자는 값을 100배 하고 퍼센트 기호를 붙입니다.

6.2.5) f-string 실용 예제

형식화된 보고서 만들기:

python
# report_example.py
product = "Laptop"
price = 899.99
quantity = 5
tax_rate = 0.08
 
subtotal = price * quantity
tax = subtotal * tax_rate
total = subtotal + tax
 
print(f"Product: {product}")  # Output: Product: Laptop
print(f"Price: ${price:.2f}")  # Output: Price: $899.99
print(f"Quantity: {quantity}")  # Output: Quantity: 5
print(f"Subtotal: ${subtotal:.2f}")  # Output: Subtotal: $4499.95
print(f"Tax (8%): ${tax:.2f}")  # Output: Tax (8%): $360.00
print(f"Total: ${total:.2f}")  # Output: Total: $4859.95

사용자 친화적인 메시지 만들기:

python
# user_messages.py
username = "Alice"
login_count = 42
last_login = "2024-03-15"
 
welcome = f"Welcome back, {username}!"
stats = f"You've logged in {login_count} times. Last login: {last_login}"
 
print(welcome)  # Output: Welcome back, Alice!
print(stats)  # Output: You've logged in 42 times. Last login: 2024-03-15

6.2.6) f-string으로 디버깅하기

Python 3.8에서는 디버깅을 위한 = 지정자를 도입했습니다. 이는 표현식과 그 값을 함께 보여 줍니다:

python
# fstring_debug.py
x = 10
y = 20
z = x + y
 
print(f"{x=}")  # Output: x=10
print(f"{y=}")  # Output: y=20
print(f"{z=}")  # Output: z=30
print(f"{x + y=}")  # Output: x + y=30

이 기능은 개발 중에 변수 값을 빠르게 확인할 때 매우 유용하며, 변수 이름을 두 번 입력할 필요가 없습니다.

6.2.7) f-string에서 중괄호 이스케이프하기

f-string 안에 실제 중괄호를 넣어야 할 때는 두 번 써야 합니다:

python
# fstring_escape.py
value = 42
# 한 쌍의 중괄호는 표현식 자리 표시자입니다
print(f"Value: {value}")  # Output: Value: 42
 
# 두 쌍의 중괄호는 실제 중괄호를 출력합니다
print(f"Use {{value}} as a placeholder")  # Output: Use {value} as a placeholder
print(f"The value is {value}, shown as {{value}}")  # Output: The value is 42, shown as {value}

6.3) format()과 포맷 지정자를 사용한 포맷팅

f-string이 현대적인 기본 선택이지만, format() 메서드 역시 여전히 널리 사용되고 있고, 알아 두면 유용한 기능을 제공합니다. 또한 f-string이 바로 이 format()을 기반으로 만들어졌기 때문에, format()을 이해하면 f-string도 더 잘 이해할 수 있습니다.

6.3.1) format()의 기본 문법

format() 메서드는 문자열 안의 중괄호 {}를 자리 표시자로 사용하고, 삽입할 값들을 인수로 넘깁니다:

python
# format_basic.py
template = "Hello, {}! You are {} years old."
message = template.format("Alice", 30)
print(message)  # Output: Hello, Alice! You are 30 years old.
 
# format()의 여러 사용 예
greeting = "Hello, {}!".format("Bob")
print(greeting)  # Output: Hello, Bob!

6.3.2) 위치 인수와 키워드 인수

위치 번호나 이름을 사용하여 어느 인수가 어느 위치에 들어갈지 제어할 수 있습니다.

위치 인수:

python
# format_positional.py
# 기본 순서 (0, 1, 2, ...)
template = "{} + {} = {}"
result = template.format(5, 3, 8)
print(result)  # Output: 5 + 3 = 8
 
# 위치를 명시적으로 지정
template = "{0} + {1} = {2}"
result = template.format(5, 3, 8)
print(result)  # Output: 5 + 3 = 8
 
# 재배치와 재사용
template = "{2} = {0} + {1}"
result = template.format(5, 3, 8)
print(result)  # Output: 8 = 5 + 3
 
# 같은 값을 여러 번 사용하기
template = "{0} times {0} equals {1}"
result = template.format(7, 49)
print(result)  # Output: 7 times 7 equals 49

키워드 인수:

python
# format_keyword.py
template = "Hello, {name}! You are {age} years old."
message = template.format(name="Alice", age=30)
print(message)  # Output: Hello, Alice! You are 30 years old.
 
# 위치 인수와 혼합 사용 (위치 인수가 먼저 와야 함)
template = "{0}, your score is {score} out of {1}"
result = template.format("Alice", 100, score=95)
print(result)  # Output: Alice, your score is 95 out of 100

6.3.3) format()에서의 포맷 지정자

포맷 지정자는 f-string에서와 마찬가지로 : 뒤에 붙여 사용합니다:

python
# format_specifiers.py
pi = 3.14159265359
 
print("{:.2f}".format(pi))  # Output: 3.14
print("{:.4f}".format(pi))  # Output: 3.1416
 
# 이름과 함께 사용
print("{value:.2f}".format(value=pi))  # Output: 3.14
 
# 여러 값에 서로 다른 포맷 지정
template = "{name}'s score is {score:.1f}%"
result = template.format(name="Bob", score=87.654)
print(result)  # Output: Bob's score is 87.7%

6.3.4) f-string 대신 format()을 사용할 때

일반적으로는 f-string이 선호되지만, format()이 유용한 상황이 몇 가지 있습니다.

1. 데이터와 분리해서 템플릿 문자열을 정의할 때:

python
# format_templates.py
# 템플릿을 한 번 정의해 두고, 서로 다른 데이터와 여러 번 사용
email_template = "Dear {name},\n\nYour order #{order_id} has shipped.\n\nThank you!"
 
# 템플릿을 서로 다른 고객에게 사용
message1 = email_template.format(name="Alice", order_id=12345)
message2 = email_template.format(name="Bob", order_id=12346)
 
print(message1)
# Output:
# Dear Alice,
#
# Your order #12345 has shipped.
#
# Thank you!
 
print(message2)
# Output:
# Dear Bob,
#
# Your order #12346 has shipped.
#
# Thank you!

2. 템플릿이 외부에서 들어오는 경우:

python
# format_external.py
# 템플릿은 설정 파일이나 데이터베이스에서 올 수도 있습니다
# (파일 읽기 방법은 24장에서 배웁니다)
user_template = input("Enter message template: ")
# 사용자가 입력: "Hello, {name}! Welcome to {place}."
 
message = user_template.format(name="Charlie", place="Python")
print(message)  # Output: Hello, Charlie! Welcome to Python.

f-string은 표현식이 즉시 평가되기 때문에 템플릿이 코드 안에 있어야 합니다. 반면 format()은 어디서 온 문자열이든 템플릿으로 사용할 수 있습니다.

6.3.5) 객체 속성과 딕셔너리 키 접근

format() 메서드는 객체의 속성(attribute)과 딕셔너리 키에도 직접 접근할 수 있습니다:

python
# format_access.py
# 딕셔너리 접근
person = {"name": "Alice", "age": 30, "city": "Boston"}
message = "Name: {0[name]}, Age: {0[age]}, City: {0[city]}".format(person)
print(message)  # Output: Name: Alice, Age: 30, City: Boston
 
# 키워드 인수와 함께 사용
message = "{p[name]} is {p[age]} years old".format(p=person)
print(message)  # Output: Alice is 30 years old

참고: 객체 속성에 대해서는 30장에서 배울 예정이지만, 여기서는 format()이 중첩된 데이터 구조에도 접근할 수 있다는 점을 보여 줍니다.

6.4) 형식화된 출력에서 숫자 정렬과 반올림

전문적으로 보여지는 출력은 값의 정렬과 숫자 포맷팅을 세심하게 조절해야 할 때가 많습니다. f-string과 format()은 잘 정렬된 표, 보고서, 화면 표시를 만들 수 있는 강력한 도구를 제공합니다.

6.4.1) 텍스트 정렬

포맷 지정자를 사용해서 값의 폭과 정렬을 제어할 수 있습니다:

python
# alignment_basic.py
# 문법: {value:width}
# 기본값은 문자열은 왼쪽 정렬, 숫자는 오른쪽 정렬입니다
 
name = "Alice"
print(f"|{name}|")      # Output: |Alice|
print(f"|{name:10}|")   # Output: |Alice     |  (왼쪽 정렬, 폭 10)
print(f"|{name:>10}|")  # Output: |     Alice|  (오른쪽 정렬)
print(f"|{name:^10}|")  # Output: |  Alice   |  (가운데 정렬)

정렬 지정자는 다음과 같습니다:

  • < : 왼쪽 정렬 (문자열의 기본값)
  • > : 오른쪽 정렬 (숫자의 기본값)
  • ^ : 가운데 정렬

숫자 정렬:

python
# alignment_numbers.py
value = 42
print(f"|{value}|")      # Output: |42|
print(f"|{value:5}|")    # Output: |   42|  (기본적으로 오른쪽 정렬)
print(f"|{value:<5}|")   # Output: |42   |  (왼쪽 정렬)
print(f"|{value:^5}|")   # Output: | 42  |  (가운데 정렬)

6.4.2) 사용자 지정 채움 문자

빈 공간을 채우는 문자를 지정할 수도 있습니다:

python
# alignment_fill.py
name = "Bob"
print(f"|{name:*<10}|")  # Output: |Bob*******|
print(f"|{name:*>10}|")  # Output: |*******Bob|
print(f"|{name:*^10}|")  # Output: |***Bob****|
 
# 눈에 띄는 구분선을 만들 때 유용합니다
print(f"{name:=^20}")    # Output: ========Bob=========

문법은 {value:fill_char align width}입니다.

6.4.3) 정렬과 숫자 포맷팅 결합하기

폭, 정렬, 숫자 포맷팅을 함께 사용할 수 있습니다:

python
# alignment_combined.py
price = 19.99
quantity = 5
total = price * quantity
 
# 폭 10, 오른쪽 정렬, 소수점 이하 2자리
print(f"Price:    ${price:>10.2f}")     # Output: Price:    $     19.99
print(f"Quantity: {quantity:>10}")      # Output: Quantity:          5
print(f"Total:    ${total:>10.2f}")     # Output: Total:    $     99.95
 
# 채움 문자를 사용한 시각적 효과
print(f"Total:    ${total:>10.2f}".replace(' ', '.'))  # Output: Total:....$.....99.95

이 장에서는 사실상 모든 Python 프로그램에서 사용하게 될 필수적인 문자열 조작 기술을 배웠습니다. 텍스트 처리를 위한 문자열 분할과 결합, f-string과 포맷 지정자를 이용한 형식화된 출력, 전문적인 화면을 위한 숫자 정렬과 포맷팅 등이었습니다.

이 기술들은 Python에서 텍스트 데이터를 다루는 기초를 이룹니다. 이제 사용자 입력을 처리하고, 형식화된 보고서를 만들고, 파일에서 온 데이터를 처리할 수 있습니다(파일 처리는 24장에서 다룰 것입니다). 앞으로 Python을 계속 학습하는 동안, 이런 문자열 처리 기법은 계속해서 사용하게 되니, 몸에 익을 때까지 충분히 연습해 두세요.

© 2025. Primesoft Co., Ltd.
support@primesoft.ai