2023. 12. 10. 21:29ㆍpython/basic
Python에서 .join()를 사용하여 많은 문자열을 효율적으로 연결
- 문자열 연결이 무엇인지, 왜 유용한지 이해하기
- 연결 연산자, + 및 += 를 사용하여 두 문자열을 연결합니다.
- .join() 메소드를 사용하여 여러 문자열을 효율적으로 연결
- 문자열 리터럴, StringIO 및 print() 과 같은 대체 연결 기술을 살펴보세요.
"Hello, " + "Pythonista!"
'Hello, Pythonista!'
head = "String Concatenation "
tail = "is Fun in Python!"
head + tail
'String Concatenation is Fun in Python!'
def age_group(age):
if 0 <= age <= 9:
result = "a Child!"
elif 9 < age <= 18:
result = "an Adolescent!"
elif 19 < age <= 65:
result = "an Adult!"
else:
result = "in your Golden Years!"
print("You are " + result)
age_group(29)
age_group(14)
age_group(68)
You are an Adult!
You are an Adolescent!
You are in your Golden Years!
연결 연산자에는 두 문자열을 함께 연결하는 단축키를 제공하는 확장 버전이 있습니다. 증가 연결 연산자 (+=)의 구문은 다음과 같습니다.
string += other_string
word = "Py"
word += "tho"
word += "nis"
word += "ta"
word
'Pythonista'
이 예에서 모든 증대 할당은 += 연산자를 사용하여 마지막 단어에 새 음절을 추가합니다.
def concatenate(iterable, sep=" "):
sentence = iterable[0]
for word in iterable[1:]:
sentence += (sep + word)
return sentence
concatenate(["Hello,", "World!", "I", "am", "a", "Pythonista!"])
'Hello, World! I am a Pythonista!'
루프 내에서 증가된 연결 연산자를 사용하여 루프의 여러 문자열을 빠르게 연결합니다
Python의 연결 연산자는 문자열 객체만 연결할 수 있습니다. 다른 데이터 유형과 함께 사용하면 TypeError:가 표시됩니다.
"The result is: " + 42
TypeError: can only concatenate str (not "int") to str
"The result is: " + "42"
'The result is: 42'
연결 연산자는 다른 유형의 피연산자를 허용하지 않습니다. 문자열만 연결합니다. 이 문제에 대한 해결 방법은 내장된 str() 함수를 명시적으로 사용하여 대상 개체를 해당 문자열 표현으로 바꿔주어야 합니다.
"The result is: " + str(42)
'The result is: 42'
참고: Python의 f-문자열은 문자열 조작을 위한 훌륭한 도구를 제공합니다. 명시적인 변환 없이도 다양한 유형의 값을 기존 문자열에 넣을 수 있습니다.
f"The result is: {42}"
'The result is: 42'
+ 및 그 변형 +=을 사용한 문자열 연결은 몇 개의 문자열만 연결해야 할 때 유용할 수 있습니다. 그러나 이러한 연산자는 많은 문자열을 단일 문자열로 결합하는 데 효율적인 선택이 아닙니다. 새 문자열을 생성하면 두 리소스가 모두 사용되기 때문에 이 동작은 추가 메모리 소비 및 처리 시간을 의미합니다.
문자열 연결 프로세스에서 구분 기호로 작동할 문자열 개체에 대해 .join() 메서드를 호출할 수 있습니다. 반복 가능한 문자열이 주어지면 .join() 포함된 모든 문자열을 하나로 효율적으로 연결합니다.
" ".join(["Hello,", "World!", "I", "am", "a", "Pythonista!"])
'Hello, World! I am a Pythonista!'
.join() 은 문자열이 아닌 개체를 직접 연결할 수 없다는 점에 유의하는 것이 중요합니다.
"; ".join([1, 2, 3, 4, 5])
TypeError: sequence item 0: expected str instance, int found
이 문제를 해결하려면 str() 및 생성기 표현식을 활용하세요.
numbers = [1, 2, 3, 4, 5]
"; ".join(str(number) for number in numbers)
'1; 2; 3; 4; 5'
스타 연산자(*)를 사용하여 반복 연결 수행
별표 연산자(*)를 사용하여 Python에서 문자열을 연결할 수도 있습니다. 이러한 맥락에서 이 연산자를 반복 연결 연산자라고 합니다. 문자열을 특정 횟수만큼 반복하여 작동합니다.
string = string * n
string *= n
이 연결 도구를 사용하는 일반적인 예는 표 형식 출력에 사용할 구분 기호 문자열을 생성해야 하는 경우입니다. 예를 들어, 목록 목록에 있는 사람에 대한 정보가 포함된 CSV 파일을 읽었다고 가정해 보겠습니다.
data = [
["Name", "Age", "Hometown"],
["Alice", "25", "New York"],
["Bob", "30", "Los Angeles"],
["Charlie", "35", "Chicago"]
]
def display_table(data):
max_len = max(len(header) for header in data[0])
sep = "-" * max_len
for row in data:
print("|".join(header.ljust(max_len) for header in row))
if row == data[0]:
print("|".join(sep for _ in row))
display_table(data)
Name |Age |Hometown
--------|--------|--------
Alice |25 |New York
Bob |30 |Los Angeles
Charlie |35 |Chicago
문자열 연결을 위한 다른 도구 탐색
문자열 리터럴 연결 활용
- 따옴표 기호를 이스케이프 처리하지 않고도 다양한 인용 스타일 사용하기
- 여러 줄에 걸쳐 긴 문자열을 편리하게 분할하기
- 문자열 부분에 주석 추가하기
phrase = (
"Guido's talk wasn't named " # String with apostrophes
'"Feeding CPython to ChatGPT"' # String with double quotes
)
print(phrase)
Guido's talk wasn't named "Feeding CPython to ChatGPT"
이 예에서는 문자열 리터럴 연결을 활용하여 문자열의 여러 부분에 주석을 추가하고 최종 문자열 내에서 큰따옴표와 작은따옴표를 이스케이프 처리합니다.
문자열 StringIO 연결하기
from io import StringIO
words = ["Hello,", "World!", "I", "am", "a", "Pythonista!"]
sentence = StringIO()
sentence.write(words[0])
6
for word in words[1:]:
sentence.write(" " + word)
sentence.getvalue()
'Hello, World! I am a Pythonista! World! I am a Pythonista!'
아래 스크립트는 내장된 input() 함수를 사용하여 사용자의 입력을 가져옵니다. 입력이 마침표, 느낌표 또는 물음표인 경우 루프가 중단되어 입력이 종료됩니다. 그런 다음 .tell() 메소드를 사용하여 버퍼가 비어 있는지 확인합니다. 이 검사에 따라 명령문은 현재 단어만 추가하거나 앞에 공백이 있는 단어를 추가합니다.
# sentence.py
from io import StringIO
sentence = StringIO()
while True:
word = input("Enter a word (or './!/?' to end the sentence): ")
if word in ".!?":
sentence.write(word)
break
if sentence.tell() == 0:
sentence.write(word)
else:
sentence.write(" " + word)
print("The concatenated sentence is:", sentence.getvalue())
Enter a word (or './!/?' to end the sentence): hello,
Enter a word (or './!/?' to end the sentence): your
Enter a word (or './!/?' to end the sentence): name?
Enter a word (or './!/?' to end the sentence):
The concatenated sentence is: hello, your name?
이 스크립트가 실제로 작동하는 방식은 다음과 같습니다.
$ python sentence.py
Enter a word (or ‘./!/?’ to end the sentence): Hello,
Enter a word (or ‘./!/?’ to end the sentence): welcome
Enter a word (or ‘./!/?’ to end the sentence): to
Enter a word (or ‘./!/?’ to end the sentence): Real
Enter a word (or ‘./!/?’ to end the sentence): Python
Enter a word (or ‘./!/?’ to end the sentence): !
The concatenated sentence is: Hello, welcome to Real Python!
StringIO을 사용하여 문자열을 연결하는 것은 연결 연산자를 사용하는 것에 대한 훌륭한 대안이 될 수 있습니다. 이 도구는 많거나 알 수 없는 수의 문자열을 처리해야 할 때 유용합니다.
print()를 사용하여 문자열 연결
words = ["Hello,", "World!", "I", "am", "a", "Pythonista!"]
print(*words)
print(*words, sep="\n")
Hello, World! I am a Pythonista!
Hello,
World!
I
am
a
Pythonista!
print() 함수는 기본값이 공백인 sep 인수를 사용합니다. 이 인수를 사용하여 연결에 대한 사용자 정의 구분 기호를 제공할 수 있습니다. 연결 컨텍스트에서 print() 의 또 다른 편리한 사용법은 연결된 문자열을 파일에 저장하는 것입니다.
words = ["Hello,", "World!", "I", "am", "a", "Pythonista!"]
with open("output.txt", "w") as output:
print(*words, sep="\n", file=output)
이 코드를 실행하면 output.txt 줄 바꿈 이스케이프 시퀀스를 구분 기호로 사용했기 때문에 한 줄에 한 단어씩 연결된 문자열이 포함됩니다.
!ls -l output.txt
-rw-rw-r-- 1 pulisul pulisul 33 12월 10 10:14 output.txt
'python > basic' 카테고리의 다른 글
Python 표준 REPL 코드와 아이디어를 빠르게 시험해 보세요 (0) | 2023.12.12 |
---|---|
Python과 PySimpleGUI를 사용하여 행맨 게임 구축 (1) | 2023.12.11 |
Python의 연산자 및 표현식 (1) | 2023.12.09 |
문자열 보간 및 서식 지정을 위한 Python의 F-String (1) | 2023.12.08 |
Python에서 명령줄용 행맨 게임 구축 (2) | 2023.12.07 |