1. ホーム
  2. python

[解決済み] 文字列から数字を削除する【クローズド

2022-03-04 23:02:55

質問

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

どのように解決するのですか?

あなたの状況には合っていますか?

>>> 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'