Pythonのstrは、Unicodeコードポイントのイミュータブルなシーケンスです。
これには、文字、発音区別符号、位置決め文字、数字、通貨記号、絵文字、句読点、空白、改行文字などが含まれます。
文字列がどんな情報をエンコードしているのか、あるいは_「コンピューターはどうやって0と1を文字に変換するのか?」_を深く知りたいなら、このブログ記事が今なお大変参考になります。
Pythonのドキュメントにも、非常に詳しいunicode HOWTOがあり、str、bytes、reモジュールにおけるUnicode仕様のサポート、ロケールに関する考慮事項、エンコーディングと変換に関するよくある問題などが解説されています。
文字列は、すべての共通シーケンス操作を実装しており、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>)で分割できます。
さらに、書式設定、組み立て、テンプレート化のためのさまざまなオプションも用意されています。
strリテラルは、一重引用符'または二重引用符"を使って宣言できます。エスケープ文字\は必要に応じて使えます。
>>> single_quoted = 'These allow "double quoting" without "escape" characters.'
>>> double_quoted = "These allow embedded 'single quoting', so you don't have to use an 'escape' character."
複数行の文字列は、'''または"""で宣言します。
>>> triple_quoted = '''Three single quotes or "double quotes" in a row allow for multi-line string literals.
Line break characters, tabs and other whitespace is fully supported. Remember - The escape "\" character is also available if needed (as can be seen below).
You\'ll most often encounter multi-line strings as "doc strings" or "doc tests" written just below the first line of a function or class definition.
They\'re often used with auto documentation ✍ tools.
'''
str(<object>)コンストラクターを使うと、他のオブジェクトから文字列を生成したり、文字列に変換したりできます。
>>> my_number = 42
>>> str(my_number)
...
"42"
str(<object>)コンストラクターは文字列への変換に使えますが、オブジェクトを_イテレートしたり_展開したりはしません。
これは、list()、set()、dict()、tuple()など他のデータ型のコンストラクターの動作とは異なり、意外な結果になることがあります。
>>> numbers = [1,3,5,7]
>>> str(numbers)
...
'[1,3,5,7]'
str内のコードポイントは、左からの0-based index番号で参照できます。
creative = '창의적인'
>>> creative[0]
'창'
>>> creative[2]
'적'
>>> creative[3]
'인'
インデックスは右からも使えます。この場合は-1-based indexから始まります。
creative = '창의적인'
>>> creative[-4]
'창'
>>> creative[-2]
'적'
>>> creative[-1]
'인'
Pythonには独立した「文字」や「ルーン」という型はないため、文字列をインデックスで参照すると、長さ1の新しいstrが生成されます。
>>> website = "exercism"
>>> type(website[0])
<class 'str'>
>>> len(website[0])
1
>>> website[0] == website[0:1] == 'e'
True
部分文字列は_スライス記法_で取り出せます。<str>[<start>:<stop>:<step>]を使うと、新しい文字列が生成されます。
結果にはstopのインデックスは含まれません。
startを指定しない場合、開始インデックスは0になります。
stopを指定しない場合、stopは文字列の末尾になります。
moon_and_stars = '🌟🌟🌙🌟🌟⭐'
>>> moon_and_stars[1:4]
'🌟🌙🌟'
>>> moon_and_stars[:3]
'🌟🌟🌙'
>>> moon_and_stars[3:]
'🌟🌟⭐'
>>> moon_and_stars[:-1]
'🌟🌟🌙🌟🌟'
>>> moon_and_stars[:-3]
'🌟🌟🌙'
文字列は<str>.split(<separator>)で小さな文字列に分割することもでき、部分文字列のlistが返されます。
<str>.split()を引数なしで使うと、空白で文字列が分割されます。
>>> cat_ipsum = "Destroy house in 5 seconds command the hooman."
>>> cat_ipsum.split()
...
['Destroy', 'house', 'in', '5', 'seconds', 'command', 'the', 'hooman.']
>>> cat_words = "feline, four-footed, ferocious, furry"
>>> cat_words.split(',')
...
['feline', ' four-footed', ' ferocious', ' furry']
>>> colors = """red,
orange,
green,
purple,
yellow"""
>>> colors.split(',\n')
['red', 'orange', 'green', 'purple', 'yellow']
文字列は+演算子で連結できます。
ただし、この方法はパフォーマンスがあまり良くなく、保守も簡単ではないため、使うのは控えめにしましょう。
language = "Ukrainian"
number = "nine"
word = "дев'ять"
sentence = word + " " + "means" + " " + number + " in " + language + "."
>>> print(sentence)
...
"дев'ять means nine in Ukrainian."
list、tuple、setなどの個々の文字列のコレクションを1つのstrにまとめる必要がある場合は、<str>.join(<iterable>)を使うのが良いでしょう。
# str.join() makes a new string from the iterables elements.
>>> chickens = ["hen", "egg", "rooster"] # Lists are iterable.
>>> ' '.join(chickens)
'hen egg rooster'
# Any string can be used as the joining element.
>>> ' :: '.join(chickens)
'hen :: egg :: rooster'
>>> ' 🌿 '.join(chickens)
'hen 🌿 egg 🌿 rooster'
# Any iterable can be used as input.
>>> flowers = ("rose", "daisy", "carnation") # Tuples are iterable.
>>> '*-*'.join(flowers)
'rose*-*daisy*-*carnation'
>>> flowers = {"rose", "daisy", "carnation"} # Sets are iterable, but output order is not guaranteed.
>>> '*-*'.join(flowers)
'rose*-*carnation*-*daisy'
>>> phrase = "This is my string" # Strings are iterable, but be careful!
>>> '..'.join(phrase)
'T..h..i..s.. ..i..s.. ..m..y.. ..s..t..r..i..n..g'
# Separators are inserted **between** elements, but can be any string (including spaces).
# This can be exploited for interesting effects.
>>> under_words = ['under', 'current', 'sea', 'pin', 'dog', 'lay']
>>> separator = ' ⤴️ under' # Note the leading space, but no trailing space.
>>> separator.join(under_words)
'under ⤴️ undercurrent ⤴️ undersea ⤴️ underpin ⤴️ underdog ⤴️ underlay'
# The separator can be composed different ways, as long as the result is a string.
>>> upper_words = ['upper', 'crust', 'case', 'classmen', 'most', 'cut']
>>> separator = ' 🌟 ' + upper_words[0] # This becomes one string, similar to ' ⤴️ under'.
>>> separator.join(upper_words)
'upper 🌟 uppercrust 🌟 uppercase 🌟 upperclassmen 🌟 uppermost 🌟 uppercut'
文字列は、すべての共通シーケンス操作をサポートしています。
個々のコードポイントは、for item in <str>でループ処理できます。
インデックス_と_要素の両方は、for index, item in enumerate(<str>)でループ処理できます。
>>> exercise = 'လေ့ကျင့်'
# Note that there are more code points than perceived glyphs or characters.
# Care should be used when iterating over languages that use
# combining characters, or when dealing with emoji.
>>> for code_point in exercise:
... print(code_point)
...
လ
ေ
့
က
ျ
င
်
့
# Using enumerate will give both the value and index position of each element.
>>> for index, code_point in enumerate(exercise):
... print(index, ": ", code_point)
...
0 : လ
1 : ေ
2 : ့
3 : က
4 : ျ
5 : င
6 : ်
7 : ့
Pythonには、検索、クリーニング、分割、変換、翻訳など、さまざまな操作を助ける豊富な文字列メソッドが用意されています。 これらのメソッドの一部は、別の演習で扱います。
Pythonには、文字列の書式設定やテンプレート化のための豊富なツールに加えて、re(正規表現)、difflib(シーケンス比較)、textwrapモジュールを使った、より高度なテキスト処理も用意されています。 Pythonでの文字列の書式設定についての優れた入門には、Real Pythonのこちらの記事をご覧ください。 文字列メソッドの入門には、同じサイトのStrings and Character Data in Pythonをご覧ください。
str(_テキスト_シーケンス)に加えて、Pythonには対応するバイナリシーケンス型があり、バイナリデータサービスにまとめられています。これは、bytes(_バイナリ_シーケンス)、bytearray、そしてバイナリデータを効率的に保存・処理するためのmemoryviewです。
さらに、Streamsを使うと、コールバックを使わずにネットワーク接続経由でバイナリデータを送受信できます。