0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

基本的な文字列操作の関数まとめ

Posted at

Pythonの組み込み関数やメソッドで文字列を操作する方法の一覧をまとめた。

1. 大文字・小文字変換

メソッド 説明
.upper() すべて大文字に変換
.lower() すべて小文字に変換
.capitalize() 先頭のみ大文字に変換
.title() 各単語の先頭を大文字に
.swapcase() 大文字・小文字を反転
text = "Hello"
print(text.upper())  # HELLO
print(text.lower())  # hello
print(text.capitalize())  # Hello
print(text.swapcase())  # hELLO

2. スライス(部分文字列の取得)

方法 説明
s[start:end] start から end-1 まで取得
s[:end] 先頭から end-1 まで取得
s[start:] start から最後まで取得
s[::-1] 逆順にする
text = "Hello"
print(text[1:4])  # ell
print(text[:3])  # Hel
print(text[2:])  # llo
print(text[::-1])  # olleH

3. 部分文字列の検索

メソッド 説明
.find(sub) sub の位置(最初)を返す
.rfind(sub) sub の位置(最後)を返す
.index(sub) sub の位置(エラーあり)
.count(sub) sub の出現回数
text = "Hello World"
print(text.find("o"))  # 4
print(text.find("World"))  # 6
print(text.find("x"))  # -1  (見つからない場合)

.index(sub) メソッドは指定した sub の位置を返すが、sub が見つからない場合 ValueError 例外を発生させる。
対して、 .find(sub) はsub が見つからない場合 -1 を返すため、エラーにならない


4. 文字列の連結

方法 説明
+ 文字列を結合
.join(iterable) リストの文字列を結合
text1 = "Hello"
text2 = "World"
print(text1 + " " + text2)  # Hello World

5. 文字列の分割

メソッド 説明
.split() スペースで分割
.split(",") 指定文字で分割
.rsplit() 右側から分割
text = "apple,banana,grape"
print(text.split(","))  # ['apple', 'banana', 'grape']

6. 文字列の置換

メソッド 説明
.replace(old, new) 文字列を置換
text = "Hello World"
print(text.replace("World", "Python"))  # Hello Python
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?