はじめに
備忘録。
特定の文字列から始まる要素のみを配列に残したい。
['hogehoge.form', 'hugahuga.form', 'hogehoge.form2']
という配列があり、hogehoge
から始まる要素のみを残し、他の要素は削除したい。
解決方法
文字列メソッドstartswith()
を使う
文字列の先頭を判別できるメソッド
moji = 'hogehoge'
# trueを返す
moji.startswith('hoge')
# falseを返す
moji.startswith('huga')
サンプルコード
# 元の配列
moji_ary = ['hogehoge.form', 'hugahuga.form', 'hogehoge.form2']
# 新しい配列new_aryに、元の配列moji_aryの要素のうち`ho`から始まる要素のみを入れる
new_ary = [hoge for hoge in moji_ary if hoge.startswith('ho')]
# 出力結果['hogehoge.form', 'hogehoge.form2']
print(new_ary)
さいごに
文字列の後尾(?)を判定するメソッドendswith()
もある。
「python 文字列操作」でググると他にも便利なものが見つかる。