strクラスには、文字列を操作したり組み立てたりするための便利なメソッドがたくさん用意されています。
検索、整形、分割、変換、翻訳など、さまざまな手法があります。
文字列はUnicodeコードポイントのシーケンスです。個々の「文字」、つまりコードポイント(長さ1の文字列)は、左から0-based indexの番号で、または右から-1-based indexの番号で参照できます。
文字列は、シーケンスの共通操作をすべて実装しています。
for item in <str>やfor index, item in enumerate(<str>)という構文を使って繰り返し処理できます。
また、<str> + <other str>や<str>.join(<iterable>)を使って連結できます。
文字列は_イミュータブル_です。つまり、メモリ上のstrオブジェクトの値は変えることができません。
strを操作する関数やメソッド(ここで学んでいるようなもの)は、元のstrを変更するのではなく、そのstrオブジェクトの新しいinstanceを返します。
以下は、Pythonの文字列メソッドの中からいくつかを抜粋したものです。 完全なリストについては、Pythonのドキュメントのstrクラスを参照してください。
<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>.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>.strip(<chars>)は、先頭と末尾の<chars>を取り除いたstrのコピーを返します。
<chars>で指定されたコードポイントはプレフィックスでもサフィックスでもありません。そのコードポイントのすべての組み合わせが、文字列の両端から取り除かれます。
<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'
この演習では、妹が学校の作文を編集するのを手伝います。先生は、正しい句読点と文法、そして優れた言葉選びを求めています。
文字列を整えて修正するタスクが4つあります。
よい作文には、きちんと整ったタイトルが必要です。
タイトルstrを仮引数として受け取り、各単語の最初の文字を大文字にする関数capitalize_title(<title>)を実装してください。
この関数は、タイトルケースにしたstrを返すようにします。
>>> capitalize_title("my hobbies")
"My Hobbies"
作文の句読点が完璧かどうかを確かめたいですね。
sentenceを仮引数として受け取る関数check_sentence_ending()を実装してください。この関数はboolを返すようにします。
>>> check_sentence_ending("I like to hike, bake, and read.")
True
作文をプロらしく見せるには、不要な空白を取り除く必要があります。
sentenceを仮引数として受け取る関数clean_up_spacing()を実装してください。
この関数は、文の先頭と末尾にある余分な空白を取り除き、更新された新しい文のstrを返すようにします。
>>> clean_up_spacing(" I like to go on hikes with my dog. ")
"I like to go on hikes with my dog."
作文を_さらに良くする_ために、一部の形容詞を類義語に置き換えることができます。
sentence、old_word、new_wordを仮引数として受け取る関数replace_word_choice()を書いてください。
この関数は、old_wordをすべてnew_wordに置き換え、更新された文の新しいstrを返すようにします。
>>> replace_word_choice("I bake good cakes.", "good", "amazing")
"I bake amazing cakes."