删除与字符串中的字母混合的数字

时间:2016-08-01 13:00:58

标签: python regex string

假设我有一个字符串,例如:

string = 'This string 22 is not yet perfect1234 and 123pretty but it can be.'

我想删除任何与混合的数字,例如'perfect1234''123pretty'但不是 '22' ,从我的字符串中得到如下输出:

string = 'This string 22 is not yet perfect and pretty but it can be.'

有没有办法在Python中使用正则表达式或任何其他方法?任何帮助,将不胜感激。谢谢!

6 个答案:

答案 0 :(得分:4)

s = 'This string 22 is not yet perfect1234 and 123pretty but it can be.'

new_s = ""
for word in s.split(' '):
    if any(char.isdigit() for char in word) and any(c.isalpha() for c in word):
        new_s += ''.join([i for i in word if not i.isdigit()])
    else:
        new_s += word
    new_s += ' '

结果:

'This string 22 is not yet perfect and pretty but it can be.'

答案 1 :(得分:3)

如果你想保留自己的数字(不是包含字母字符的单词的一部分),这个正则表达式将完成这项工作(但可能有办法让它更简单):

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,因为它不是单词的一部分。

答案 2 :(得分:1)

import re
re.sub(r'\d+', '', string)

答案 3 :(得分:0)

下面的代码检查每个字符的数字。如果它不是数字,则将字符添加到更正字符串的末尾。

string = 'This string is not yet perfect1234 and 123pretty but it can be.'

CorrectedString = ""
for characters in string:
    if characters.isdigit():
        continue
    CorrectedString += characters

答案 4 :(得分:0)

您可以通过简单地加入函数以及无需导入任何内容来尝试此操作

str_var='This string is not yet perfect1234 and 123pretty but it can be.'

str_var = ''.join(x for x in str_var if not x.isdigit())
print str_var

输出:

'This string is not yet perfect and pretty but it can be.'

答案 5 :(得分:0)

print(''.join(x for x in strng if not x.isdigit()).replace(' ',' '))

p.s。删除数字后。用单个空格替换双精度空格

输出:

This string is not yet perfect and pretty but it can be.