さわやかに

Pythonのことだったり子供のことだったり

Python 文字列操作

文字列の分割

s1 = 'apple,orange,peach'
s1.split(',')
# output -> ['apple', 'orange', 'peach']

文字列の結合

s2 = ['apple', 'orange', 'peach']
'\n'.join(s2)
# output -> 'apple\norange\npeach'

左右の空白の削除

s3 = ' apple '
s3.strip() # 左右
# output -> 'apple'
s3.rstrip() # 右
# output -> ' apple'
s3.lstrip() # 左
# output -> 'apple '

末尾のチェック

ファイルの拡張子確認などに

s4 = 'sample.jpg'
s4.endswith(('jpg', 'gif', 'png')) #リストはダメ。タプルで指定
# output -> True