文字列操作
Pythonでは文字列は非常に重要な役割を果たします。文字列は str
クラスのオブジェクトとして扱われ、次のようなさまざまな操作が可能です。
文字列の作成
- 単一引用符 (
'
)、二重引用符 ("
) で囲む - 三重引用符 (
"""
や'''
) で複数行の文字列を作成可能
str1 = 'Hello, World!'
str2 = "Python's strings"
str3 = """This is
a multi-line
string."""
文字列の連結
-
+
演算子を使って文字列を連結できます
str1 = 'Hello, '
str2 = 'World!'
str3 = str1 + str2 # 'Hello, World!'
インデックスとスライシング
- 文字列の各文字にはインデックス番号が割り当てられています
-
[]
を使ってインデックスまたはスライスを指定できます
str1 = 'Hello, World!'
print(str1[0]) # 'H'
print(str1[-1]) # '!' (マイナスインデックスで後ろから数えられる)
print(str1[2:7]) # 'llo, '
print(str1[:5]) # 'Hello'
print(str1[7:]) # 'World!'
文字列メソッド
- 文字列には便利なメソッドがたくさん用意されています
str1 = 'Hello, World!'
print(str1.upper()) # 'HELLO, WORLD!'
print(str1.lower()) # 'hello, world!'
print(str1.strip()) # 'Hello, World!' (前後の空白を削除)
print(str1.replace('l', 'L')) # 'HeLLo, WorLd!'
print(str1.split(',')) # ['Hello', ' World!']
print(' '.join(['Hi', 'there'])) # 'Hi there'
print(str1.find('o')) # 4 (見つからない場合は-1が返される)
print(str1.count('l')) # 3
フォーマット
- 文字列中に値を埋め込むためのいくつかの方法があります
name = 'Alice'
age = 25
# 古い形式の文字列フォーマット
print('My name is %s and I am %d years old.' % (name, age))
# My name is Alice and I am 25 years old.
# str.format()メソッド
print('My name is {} and I am {} years old.'.format(name, age))
# My name is Alice and I am 25 years old.
# f-strings (Python 3.6以降)
print(f'My name is {name} and I am {age} years old.')
# My name is Alice and I am 25 years old.
正規表現
- 正規表現を使うと、より高度な文字列処理が可能になります
-
re
モジュールを使用します
import re
text = 'Hello, 123 World. 456 Example.'
# 検索と置換
print(re.sub(r'\d+', 'NUM', text)) # 'Hello, NUM World. NUM Example.'
# 値の抽出
matches = re.findall(r'\d+', text)
print(matches) # ['123', '456']
文字列操作は、ファイル処理、ウェブスクレイピング、データ分析など、様々な場面で活用されます。Pythonには文字列を扱うための豊富な機能が用意されているので、状況に応じて適切に利用することが重要です。