[英]How to replace a number in a string in Python?
我需要搜索一個字符串並檢查其名稱中是否包含數字。 如果是這樣,我想什么都不用替換它。 我已經開始做這樣的事情,但我沒有找到解決我的問題的方法。
table = "table1"
if any(chr.isdigit() for chr in table) == True:
table = table.replace(chr, "_")
print(table)
# The output should be "table"
有任何想法嗎?
你可以通過許多不同的方式做到這一點。 以下是使用re模塊的方法:
import re
table = 'table1'
table = re.sub('\d+', '', table)
如果您不想導入任何模塊,您可以嘗試:
table = "".join([i for i in table if not i.isdigit()])
這聽起來像是str
的.translate
方法的任務,你可以做
table = "table1"
table = table.translate("".maketrans("","","0123456789"))
print(table) # table
maketrans
的 2 個第一個參數用於逐字符替換,因為我們不需要它,所以我們使用空str
s,第三個(可選)參數是要刪除的字符。
char_nums = [chr for chr in table if chr.isdigit()]
for i in char_nums:
table = table.replace(i, "")
print(table)
table = "table123"
for i in table:
if i.isdigit():
table = table.replace(i, "")
print(table)
我發現這可以快速刪除數字。
table = "table1"
table_temp =""
for i in table:
if i not in "0123456789":
table_temp +=i
print(table_temp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.