如何在 Python 中刪除字串中的數字?


你可以建立一個數組來追蹤字串中所有非數字字元。最後使用 "".join 方法將此陣列連線起來。 

示例

my_str = 'qwerty123asdf32'
non_digits = []
for c in my_str:
   if not c.isdigit():
      non_digits.append(c)
result = ''.join(non_digits)
print(result)

輸出

這會得到以下輸出

qwertyasdf

示例

你也可以使用一行 Python 列表推導來實現這一點。 

my_str = 'qwerty123asdf32'
result = ''.join([c for c in my_str if not c.isdigit()])
print(result)

輸出

這會得到以下輸出

qwertyasdf

更新於: 05-Mar-2020

141 次瀏覽

開啟您的 職業

透過完成課程取得認證

開始
廣告
© . All rights reserved.