Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@c6tower

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

More than 1 year has passed since last update.

はじめに

備忘録。
特定の文字列から始まる要素のみを配列に残したい。
['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
Help us understand the problem. What is going on with this article?
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
c6tower
メモついでに書いている記事多め。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?