2

我有几个字符串(每个字符串都是一组单词),其中包含特殊字符。我知道使用 strip() 函数,我们可以从任何字符串中删除所有出现的仅一个特定字符。现在,我想删除一组特殊字符(包括 !@#%&*()[]{}/?<> )等。

从字符串中删除这些不需要的字符的最佳方法是什么。

in-str = "@John,这真是太棒了#week-end%,你怎么样 "

out-str = "约翰,这是一个美妙的周末,你呢?"

4

4 回答 4

2
import string

s = "@John, It's a fantastic #week-end%, How about () you"
for c in "!@#%&*()[]{}/?<>":
    s = string.replace(s, c, "")

print s

打印“约翰,这是一个美妙的周末,你呢”

于 2013-05-13T14:40:26.783 回答
1

strip函数仅删除前导字符和尾随字符。出于您的目的,我将使用 pythonset来存储您的字符,迭代您的输入字符串并从set. 根据其他stackoverflow文章,这应该是有效的。最后,只需通过巧妙的" ".join(output_string.split())构造删除双空格。

char_set = set("!@#%&*()[]{}/?<>")
input_string = "@John, It's a fantastic #week-end%, How about () you"
output_string = ""

for i in range(0, len(input_string)):
    if not input_string[i] in char_set:
        output_string += input_string[i]

output_string = " ".join(output_string.split())
print output_string
于 2013-05-13T14:35:19.823 回答
1

试试这个:

import re

foo = 'a..!b...c???d;;'
chars = [',', '!', '.', ';', '?']

print re.sub('[%s]' % ''.join(chars), '', foo)

我想这就是你想要的。

于 2013-05-13T14:41:39.740 回答
0

尝试

s = "@John, It's a fantastic #week-end%, How about () you"
chars = "!@#%&*()[]{}/?<>"
s_no_chars = "".join([k for k in s if k not in chars])
s_no_chars_spaces = " ".join([ d for d in "".join([k for k in s if k not in chars]).split(" ") if d])
于 2013-05-13T17:05:51.613 回答