删除带有特殊字符的完整字符串

时间:2019-05-29 06:09:36

标签: python-3.x

我想删除一个包含特殊字符的完整字符串。

输入为["i am in jersey1&2","this code is %bdn2*nn"]

预期输出为["i am in","this code is"]

import re

Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]

Dsp1 = []

for i in Dsp:
    Dsp = [re.sub('^\W+$'," ",j) for j in i]
    Dsp1.append("".join(Dsp))

我知道了

Dsp1 = ["i am in jersey12","this code is bdn2nn"]

但预期输出是

Dsp1 = ["i am in", "this code is"]

2 个答案:

答案 0 :(得分:5)

使用str.isalpha

Input = ["i am in jersey1&2","this code is %bdn2*nn"]

for i in Input:
    print(" ".join(j for j in i.split() if j.isalpha()))

输出:

i am in
this code is

答案 1 :(得分:3)

您期望re.sub在单词级别进行匹配和替换,其中单词是由字符串中的空格分隔的子字符串。正则表达式将在字符级别进行匹配,除非您设法以其他方式告诉它们(这有点复杂),或者在应用特殊字符匹配的正则表达式之前在空白处分割了字符串:

Dsp = ["i am in jersey1&2","this code is %bdn2*nn"]
Dsp1 = []

for sentence in Dsp:
  cleaned_sentence = []
  for word in sentence.split(' '):
    if not re.search(r'\W'):
      cleaned_sentence.append(word)
  DSP1.append(' '.join(cleaned_sentence))

print(DSP1)
# ['i am in', 'this code is']