トラック
/
Python
Python
/
シラバス
/
文字列メソッド
文字

文字列メソッド の Python

60個の演習

文字列メソッドについて

strは、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>)で分割できます。 そのほかにも、さまざまな書式設定や組み立てのオプションがあります。

文字列をさらに操作するために、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では、接頭辞と接尾辞の削除をずっと簡単にする2つの新しい文字列メソッドが導入されました。

<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ドキュメントのUnicodeの使い方では、Pythonで文字列を扱うためのUnicode、エンコーディング、バイトなどの技術的な考慮事項が詳しく説明されています。

Pythonはreモジュールを通じて正規表現もサポートしています。これについては、今後の概念で扱います。

GitHubで編集 リンクは新しいウィンドウまたはタブで開きます

文字列メソッドを学習する

練習はロックされています

文字列メソッドを練習するには、あと3個の演習のロックを解除してください