Pythonにおける文字列操作
この記事ではPythonにおける文字列操作について説明します。
文字列の作成や連結方法、検索や置き換えなどの各種の文字列操作についてコードサンプルと共に学べます。
YouTube Video
Pythonにおける文字列操作
Pythonにおける文字列操作には、多種多様な方法があります。以下は、よく使われる文字列操作の紹介です。
文字列の作成
Pythonでは、文字列はシングルクォート '、ダブルクォート "、トリプルクォート(''', """) を使って作成できます。
1single_quoted = 'Hello'
2double_quoted = "World"
3multi_line = '''This is
4a multi-line
5string'''
6
7print(single_quoted)
8print(double_quoted)
9print(multi_line)- このコードは、Pythonでシングルクォート、ダブルクォート、トリプルクォートを使った文字列の作成と表示方法を示しています。
文字列の連結
文字列を連結するには、+演算子やf文字列、str.formatメソッドを使用します。
1# + operator
2name = "John"
3greeting = "Hello, " + name + "!"
4print(greeting)
5
6# f-string (available in Python 3.6 and above)
7greeting_f = f"Hello, {name}!"
8print(greeting_f)
9
10# str.format method
11greeting_format = "Hello, {}!".format(name)
12print(greeting_format)- このコードは、Pythonで文字列を
+演算子、f文字列、str.formatメソッドを使って連結する方法を示しています。
文字列の繰り返し
文字列を繰り返すには、*演算子を使用します。
1repeat = "ha" * 3 # Result: "hahaha"
2print(repeat)- このコードは、Pythonで
*演算子を使って文字列を繰り返す方法を示しています。
文字列の長さ
文字列の長さを取得するためには、len関数を使用します。
1name = "John"
2greeting = "Hello, " + name + "!"
3
4# Returns the length of the string greeting
5length = len(greeting)
6print(length)- このコードは、Pythonで
len関数を使って文字列の長さを取得する方法を示しています。
インデックスとスライス
文字列中の特定の文字や部分文字列を取得するためには、インデックスやスライスを使います。
1word = "Python"
2
3first_char = word[0] # P
4last_char = word[-1] # n
5print(first_char)
6print(last_char)
7
8# Slice
9sliced_word = word[1:4] # yth
10reversed_word = word[::-1] # nohtyP
11print(sliced_word)
12print(reversed_word)- このコードは、Pythonでインデックスやスライスを使って文字列の特定の文字や部分文字列を取得する方法を示しています。
文字ごとの処理
文字列はシーケンス型として扱えるため、for ループを使って文字ごとに処理することができます。
1text = "Python"
2
3# Iterate each character
4for char in text:
5 print(char)- {^ i18n_speak
このコードは、文字列
Pythonを1文字ずつ取り出して順番に表示する方法を示しています。^}
文字列の検索と置換
str.findやstr.replaceメソッドを使用して文字列を検索・置換します。
1sentence = "She sells sea shells on the sea shore."
2
3# Returns the index of the first occurrence of "sea": 10
4index = sentence.find("sea")
5print(index)
6
7# Replace "sea" with "ocean"
8replaced_sentence = sentence.replace("sea", "ocean")
9print(replaced_sentence)- このコードは、Pythonで
str.findメソッドを使って文字列を検索し、str.replaceメソッドで文字列を置換する方法を示しています。
大文字・小文字変換
文字列を大文字または小文字に変換するには、str.upperやstr.lower, str.capitalize, str.titleを使用します。
1text = "hello world"
2upper_text = text.upper() # "HELLO WORLD"
3lower_text = text.lower() # "hello world"
4capitalized_text = text.capitalize() # "Hello world"
5title_text = text.title() # "Hello World"
6
7print(upper_text)
8print(lower_text)
9print(capitalized_text)
10print(title_text)- このコードは、Pythonで文字列を大文字・小文字やタイトル形式に変換する方法を示しています。
文字列の分割と結合
文字列を特定の区切り文字で分割するにはstr.splitを使用し、リストの要素を結合するにはstr.joinを使用します。
1csv = "apples,bananas,cherries"
2fruits = csv.split(",") # ["apples", "bananas", "cherries"]
3joined_fruits = ", ".join(fruits) # "apples, bananas, cherries"
4
5print(fruits)
6print(joined_fruits)- このコードは、Pythonで
str.splitを使って文字列を分割し、str.joinを使ってリスト要素を結合する方法を示しています。
余白の削除
文字列から余白を削除するにはstr.strip, str.lstrip, str.rstripを使用します。
1whitespace = " hello "
2stripped = whitespace.strip() # "hello"
3lstripped = whitespace.lstrip() # "hello "
4rstripped = whitespace.rstrip() # " hello"
5
6print(stripped)
7print(lstripped)
8print(rstripped)- このコードは、Pythonで
str.strip、str.lstrip、str.rstripを使って文字列の前後や片側の余白を削除する方法を示しています。
まとめ
これらの操作を組み合わせることで、Pythonでさまざまな文字列操作が可能になります。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。