str은 유니코드 코드 포인트의 불변 시퀀스예요.
여기에는 문자, 발음 구별 기호, 위치 지정 문자, 숫자, 통화 기호, 이모지, 문장 부호, 공백, 줄 바꿈 등이 포함될 수 있어요.
문자열은 모든 일반 시퀀스 연산을 구현하며, for item in <str> 또는 for index, item in enumerate(<str>) 문법으로 반복할 수 있어요.
개별 코드 포인트(길이가 1인 문자열)는 왼쪽에서부터 0-based index 번호로, 또는 오른쪽에서부터 -1-based index 번호로 참조할 수 있어요.
문자열은 <str> + <other str> 또는 <str>.join(<iterable>)로 연결하고 <str>.split(<separator>)로 분할할 수 있어요.
그 밖에도 다양한 형식 지정 및 조합 옵션을 제공해요.
문자열을 더 다양하게 다루기 위해, Python은 검색, 정리, 변환, 번역 등 여러 작업을 위한 풍부한 문자열 메서드 집합을 제공해요.
자주 사용되는 str 메서드로는 다음이 있어요:
<str>.startswith(<substr>)와 <str>.endswith(<substr>)로 접두사/접미사 확인하기<str>.title(), <str>.upper()/<str>.lower(), <str>.swapcase() 같은 메서드로 문자열 대소문자 바꾸기<str>.strip(<chars>), <str>.lstrip(<chars>), <str>.rstrip(<chars>)를 사용해 문자열의 앞뒤 문자 제거하기<str>.replace(<old>, <new>) 메서드로 부분 문자열 바꾸기_불변_이기 때문에, str 객체의 메모리상 값은 바뀔 수 없어요. 문자열을 수정하는 것처럼 보이는 메서드는 그 str 객체의 새 복사본 또는 인스턴스를 반환해요.
<str>.endswith(<suffix>)는 문자열이 <suffix>로 끝나면 True를, 그렇지 않으면 False를 반환해요.
>>> 'My heart breaks. 💔'.endswith('💔')
True
>>> 'cheerfulness'.endswith('ness')
True
# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False
>>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False
<str>.title()은 문자열을 분석해 발견된 각 "단어"의 첫 "문자"를 대문자로 만들어요.
Python에서는 이것이 사용되는 언어 코덱과 특정 언어가 단어와 문자를 표현하는 방식에 크게 의존해요.
언어나 문자 집합에 따라 로케일 규칙이 적용될 수도 있어요.
>>> man_in_hat_th = 'ผู้ชายใส่หมวก'
>>> man_in_hat_ru = 'мужчина в шляпе'
>>> man_in_hat_ko = '모자를 쓴 남자'
>>> man_in_hat_en = 'the man in the hat.'
>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'
>>> man_in_hat_ru.title()
'Мужчина В Шляпе'
>>> man_in_hat_ko.title()
'모자를 쓴 남자'
>> man_in_hat_en.title()
'The Man In The Hat.'
<str>.strip(<chars>)은 앞뒤의 <chars>를 제거한 str의 복사본을 반환해요.
<chars>에 지정된 코드 포인트는 접두사나 접미사가 아니에요. 문자열의 양쪽 끝에서부터 코드 포인트의 모든 조합이 제거돼요.
<chars>에 아무것도 지정하지 않으면, 모든 공백 코드 포인트 조합이 제거돼요.
왼쪽 또는 오른쪽만 제거하고 싶다면, <str>.lstrip(<chars>)와 <str>.rstrip(<chars>)를 사용할 수 있어요.
# This will remove "https://", because it can be formed from "/stph:".
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'
# Removal of all whitespace from both ends of the str.
>>> ' 🐪🐪🐪🌟🐪🐪🐪 '.strip()
'🐪🐪🐪🌟🐪🐪🐪'
>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'
# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'
>>> ' unaddressed '.strip('dnue ')
'address'
<str>.replace(<substring>, <replacement substring>)는 <substring>의 모든 항목을 <replacement substring>로 바꾼 문자열 복사본을 반환해요.
아래에 사용된 인용구는 Lewis Carroll의 The Hunting of the Snark에서 가져왔어요.
# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
As he landed his crew with care;
Supporting each man on the top of the tide
By a finger entwined in his hair.
"Just the place for a Snark! I have said it twice:
That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
What I tell you three times is true."
'''
>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n As he landed his crew with care;\nSupporting each man on the top of the tide\n By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n What I tell you three times is true."\n'
>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'
🌟Python 3.9에서 새로 추가됨
Python 3.9는 접두사와 접미사 제거를 훨씬 쉽게 해 주는 두 가지 새로운 문자열 메서드를 도입했어요.
<str>.removeprefix(<substring>)는 접두사를 제거한 문자열(string[len(<substring>):])을 반환해요. <substring>이 없으면 원본 문자열의 복사본이 반환돼요.
# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'
<str>.removesuffix(<substring>)는 접미사를 제거한 문자열(string[:-len(substring)])을 반환해요. <substring>이 없으면 원본 문자열의 복사본이 반환돼요.
# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'
더 많은 예제와 메서드는 비공식 튜토리얼이 좋은 출발점이에요. Python 문서의 How to Unicode는 유니코드, 인코딩, 바이트, 그리고 Python에서 문자열을 다룰 때의 기타 기술적 고려 사항에 대한 자세한 내용을 제공해요.
Python은 re 모듈을 통해 정규 표현식도 지원하는데, 이는 나중에 다룰 개념에서 설명할 예정이에요.