如何在Python中替换字符串中的数字?

Cat*_*iro 5 python replace

我需要搜索一个字符串并检查它的名称中是否包含数字。如果是这样的话,我想什么都不能代替。我已经开始做类似的事情,但我没有找到解决我的问题的方法。

table = "table1"

if any(chr.isdigit() for chr in table) == True:
    table = table.replace(chr, "_")
    print(table)

# The output should be "table"
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Ctr*_*rlZ 7

您可以通过多种不同的方式来做到这一点。以下是使用re模块完成此操作的方法:

import re

table = 'table1'

table = re.sub(r'\d+', '', table)
Run Code Online (Sandbox Code Playgroud)