LoginSignup
6
21

More than 5 years have passed since last update.

Python 文字列操作チートシート

Last updated at Posted at 2018-11-19

pythonの文字列操作チートシート
実行環境は下記

$ python -V
Python 3.6.6

文字列基礎

文字列は 「 ‘ 」(シングルクォーテーション)と「 ” 」(ダブルクォーテーション)の両方で表現する
クォート記号3つで複数行に分けて書く事も出来ます。

文字列結合

2つの文字列を1つの文字列へする方法

str1 = "hello"
str2 = "world"

#「+」演算子
str1 = str1 + str2
# or
str1 += str2 

# リテラルを並べて書いても連結される(変数は不可)
str4 = 'aaa''bbb''ccc'

# sprint風な書き方もできる
print("%s %s" % (str1, str2))
print('{} {}'.format(str1, str2)) #python3ではこちら推奨
print(f'{str1} {str2}') #Python3.6以降で使える

# 型の違う文字列でも結合可能
print('{} {}'.format(str1, int1))
print(f'{str1} {int1}')

# 「join()」使用
words = ["Hello", "World", "!"]
print(" ".join(words)) 
## => Hello World !

文字列分割

指定の文字列に対して,区切り文字で分割したリストを返します.

str = "A B C D"
## 「split」使用 .split(区切り文字, 分割数)
print(str.split())
## => ["A", "B", "C", "D"]

str = "HelloWorld"
## 「rsplit」使用 .rsplit(区切り文字, 分割数)
print(str.rsplit("l",1)) ## => ['HelloWor', 'd']

文字列置換

文字列を置換する方法について説明します。

# replace()を使用
str = "123123123"
## 指定文字列を置換する(指定したワード全て)
print(str.replace("123", "hoge")) 
## => hogehogehoge

# 置換回数を1回にして指定文字列を置換する
print(a.replace("123", "hoge", 1)) 
## => hoge123123
import re

# 正規表現を使用しての置換
str1 = 'I like orange.'
print(re.sub(r'[a-z]+', 'xxx', str1))
# => 'I xxx xxx.'

正規表現に関しては以下にまとまっていますのでご参照ください
https://docs.python.jp/3/library/re.html

文字列検査

# find()メソッド
# 一致する文字列が出現する位置を返す
str1 = "hello world"
print(str1.find('o'))
# => 4
print(str1.rfind('o')) #逆側から検索
# => 10

# 第二引数で位置を指定すること出来る
print(str1.find('o', 5))
# => 7

# 単純に存在の有無を調べるなら「in」を使用
print('hello' in 'hello world')
# => True
print('hello Japan' in 'hello world')
# => False

# findall()メソッド 正規表現使用
print(re.findall('o.', 'hello world'))
# => ['o ', 'or']
print(re.findall('oh', 'hello world'))
# => []

パディング

桁合わせするにはいくつか方法があります。

# 右寄せゼロ埋め: zfill()

str1 = 1234
print(str1.zfill(8))
## => 00001234

# 数字以外でも可
str2 = 'abcd'
print(str2.zfill(8))
## => 0000abcd

# 右寄せ、左寄せ、中央寄せ: rjust(), ljust(), center()
str1 = '1234'

print(str1.rjust(8, '0'))
# 00001234

print(str1.ljust(8, '0'))
# 12340000

print(str1.center(8, '0'))
# 00123400

# %演算子を使う方法もある
num = 50
num_pad = '%04d' % number
print(number_pad)
## => '0050'

# formatを使う方法もある
print('{:0>8}'.format(str1))
## => 00001234
print('{:0^8}'.format(str1))
## => 00123400
print('{:0<8}'.format(str1))
## => 12340000
print('{:04}'.format(num))
## => 0050

# f-string を使う方法もある
print(f'{str1:0>8}')
## => 00001234
print(f'{str1:0^8}')
## => 00123400
print(f'{str1:0<8}')
## => 12340000
print(f'{num:04}')
## => 0050

空白削除

文字列の中に存在する空白が不要なときの処理

str1 = "    Hello World!!    "

# 単語の間にある空白は削除したくない場合
print(str1.strip())
# => "Hello World!!"

# 左側にある空白のみ削除したい場合
print(str1.lstrip())
# => "Hello World!!    "

# 右側にある空白のみ削除したい場合
print(str1.rstrip())
# => "    Hello World!!"

大文字/小文字変換

文字列を大文字から小文字へ変換するメソッドとして「lower」があります。
逆に小文字から大文字へ変換するメソッドとして「upper」があります。

str1 = "abcDEfg"

print(str1.upper())
# => ABCDEFG

print(str1.lower())
# => abcdefg

型変換

# intからstrへ変換
str1 = str(int1)

# floatも可
str2 = str(float1)

まとめ

大体覚えていますがとりあえずまとめて見ました。

6
21
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
6
21