如何在 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

更新於: 2020-03-05

142 次瀏覽

開啟你的 職業生涯

完成課程即獲得認證

開始
廣告
© . All rights reserved.