0
0

More than 3 years have passed since last update.

【Python】特定の文字列で始まる要素のみを配列に残す

Posted at

はじめに

備忘録。
特定の文字列から始まる要素のみを配列に残したい。
['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 文字列操作」でググると他にも便利なものが見つかる。

参考サイト

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