文字列から数字を削除する [closed] 質問する

文字列から数字を削除する [closed] 質問する

文字列から数字を削除するにはどうすればよいですか?

ベストアンサー1

これはあなたの状況に有効でしょうか?

>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'

これはリストの内包表記を利用しており、ここで起こっていることは次の構造に似ています。

no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '', 
# which puts all of the characters together.
result = ''.join(no_digits)

@AshwiniChaudhary と @KirkStrauser が指摘しているように、実際にはワンライナーで括弧を使用する必要はなく、括弧内の部分をジェネレータ式にします (リストの内包表記よりも効率的です)。これが課題の要件に合わない場合でも、最終的には読むべき内容です :) :

>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'

おすすめ記事