无法从长字符串中删除某些符号

Can't remove some symbols from a long string

在过去的几个小时里,我一直在尝试一次从长字符串中踢出一些符号,但找不到关于如何删除它们的任何想法。如果我选择使用 .replace() 函数,这将是一种更丑陋的方法,因为符号的数量超过一个,并且函数变得过长以覆盖所有符号。任何删除它们的替代方法将不胜感激。

这是我试过的:

exmpstr = "Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control"

print(exmpstr.replace("'","").replace("(","").replace(")","").replace("&",""))
print(exmpstr.replace("['()&]","")) #I know it can't be any valid approach but I tried

我想删除的是该字符串中的这些符号 '()&,而不是我尝试使用 .replace() 函数的方式。

您可以使用带有替换的 for 循环:

for ch in "['()&]":
    exmpstr = exmpstr.replace(ch, '')

或者您可以使用正则表达式

import re
exmpstr = re.sub(r"[]['()&]", "", exmpstr)

实际上,您的第二次尝试已经非常接近了。使用正则表达式 sub 进行替换,可以这样完成:

import re
regex = r"['()&]"

test_str = "\"Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control\""
subst = ""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
    print (result)

如果您想将 & 替换为 and 运行 另一个:

result = re.sub(r" & ", " and ", test_str, 0, re.MULTILINE)

并从第一个 regex character group ['()&] 中删除 &

它也有作用:

exmpstr = "Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control"
expectedstr = ''.join(i for i in exmpstr if i not in "'()&")
print(expectedstr)