最近几个小时,我一直在尝试从长字符串中踢出一些符号,但是我找不到如何删除它们的任何想法。如果我选择使用.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()
函数的方式。
答案 0 :(得分:8)
您可以将for循环与replace一起使用:
for ch in "['()&]":
exmpstr = exmpstr.replace(ch, '')
或者您可以使用正则表达式
import re
exmpstr = re.sub(r"[]['()&]", "", exmpstr)
答案 1 :(得分:1)
它也可以解决问题:
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)
答案 2 :(得分:0)
实际上,您的第二次尝试非常接近。使用正则表达式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 &
中删除['()&]
。
答案 3 :(得分:-2)
使用re
模块:
import re
exmpstr = "Hi there Sam! Don't you know that Alex (the programmer) created something useful or & easy to control"
s = re.sub('(\,)|(\[)|(\')|(\()|(\))|(\&)|(\])|(\')', '', exmpstr)
print(s)
输出:
嗨,山姆!您是否不知道程序员Alex创造了一些东西 有用或易于控制