从单词中删除数字

时间:2018-06-06 13:25:34

标签: python regex

假设我有一个包含单词,整数及其组合的句子:

"This is a string with an integer 1 and a 2 and a 3 and a 1A69 and a 1B and a C3"

是否可以从包含字母整数的单词中删除所有整数?即,我希望以上内容成为

"This is a string with an integer 1 and a 2 and a 3 and a A and a B and a C"

2 个答案:

答案 0 :(得分:3)

一个选项可能是删除前面的数字(看后面 ?<=语法)或跟随(使用 lookahead ?=语法)用信:

import re
s = "This is a string with an integer 1 and a 2 and a 3 and a 1A69 and a 1B and a C3"

re.sub(r'\d+(?=[a-zA-Z])|(?<=[a-zA-Z])\d+', '', s)
# 'This is a string with an integer 1 and a 2 and a 3 and a A and a B and a C'

答案 1 :(得分:1)

或者,没有正则表达式:

def remove_digits(s):
    return ''.join([x for x in s if not x.isdigit()])

def is_combined(s):
    return any(x.isalpha() for x in s) and any(x.isdigit() for x in s)

' '.join([remove_digits(x) if is_combined(x) else x for x in test.split()])