Help us understand the problem. What is going on with this article?

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

はじめに

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

参考サイト

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした