假设我有一个字符串,例如:
string = 'This string 22 is not yet perfect1234 and 123pretty but it can be.'
我想删除任何数字与单词混合的, 例如'perfect1234' and '123pretty', but not '22',从我的字符串中得到如下输出:
'perfect1234'
'123pretty'
'22'
string = 'This string 22 is not yet perfect and pretty but it can be.'
有没有办法在Python中使用正则表达式或任何其他方法来做到这一点?任何帮助,将不胜感激。谢谢你!
如果你想保留数字本身(不是带有字母字符的单词的一部分),这个正则表达式可以完成这项工作(但可能有一种方法可以使它更简单):
import re pattern = re.compile(r"\d*([^\d\W]+)\d*") s = "This string is not yet perfect1234 and 123pretty but it can be. 45 is just a number." pattern.sub(r"\1", s) 'This string is not yet perfect and pretty but it can be. 45 is just a number.'
这里留下了 45,因为它不是单词的一部分。