Pythonで文字列を区切る方法(split/rsplit)

投稿者: | 2020年9月25日

Pythonで文字列を区切る方法(split/rsplit)です

文字列を前から区切る場合はsplitを使います

# 対象文字列
test = "1,2,3,4,5"

# split 文字列の前から区切る
test1 = test.split(",")
print(test1)

# split 文字列の前から3番目まで区切る
test2 = test.split(",", 3)
print(test2)

splitの実行結果

['1', '2', '3', '4', '5']
['1', '2', '3', '4,5']

文字列を後ろから区切る場合はrsplitを使います

# 対象文字列
test = "1,2,3,4,5"

# rsplit 文字列の後ろから区切る
test3 = test.rsplit(",")
print(test3)

# rsplit 文字列の後ろから3番目まで区切る
test4 = test.rsplit(",", 3)
print(test4)

rsplit の実行結果

['1', '2', '3', '4', '5']
['1,2', '3', '4', '5']