我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
当前回答
这里有一些可能的方法来完成这个任务:
def attempt1(string):
return "".join([v for v in string if v not in ("a", "e", "i", "o", "u")])
def attempt2(string):
for v in ("a", "e", "i", "o", "u"):
string = string.replace(v, "")
return string
def attempt3(string):
import re
for v in ("a", "e", "i", "o", "u"):
string = re.sub(v, "", string)
return string
def attempt4(string):
return string.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")
for attempt in [attempt1, attempt2, attempt3, attempt4]:
print(attempt("murcielago"))
附注:在使用" ?.!/;:"的例子中使用元音…是的,“murcielago”在西班牙语里是蝙蝠的意思…有趣的单词,因为它包含了所有的元音:)
PS2:如果你对性能感兴趣,你可以用一个简单的代码来衡量这些尝试:
import timeit
K = 1000000
for i in range(1,5):
t = timeit.Timer(
f"attempt{i}('murcielago')",
setup=f"from __main__ import attempt{i}"
).repeat(1, K)
print(f"attempt{i}",min(t))
在我的盒子里,你会得到:
attempt1 2.2334518376057244
attempt2 1.8806643818474513
attempt3 7.214925774955572
attempt4 1.7271184513757465
因此,对于这个特定的输入,尝试4似乎是最快的。
其他回答
#!/usr/bin/python
import re
strs = "how^ much for{} the maple syrup? $20.99? That's[] ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!|a|b]',r' ',strs)#i have taken special character to remove but any #character can be added here
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)#for removing special character
print nestr
>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if c not in '?:!/;' )
'abc#@efg12'
提问者几乎就说到了。像Python中的大多数事情一样,答案比您想象的要简单。
>>> line = "H E?.LL!/;O:: "
>>> for char in ' ?.!/;:':
... line = line.replace(char,'')
...
>>> print line
HELLO
你不需要做嵌套的if/for循环,但你确实需要单独检查每个字符。
如果你想让你的字符串只允许使用ASCII码,你可以使用这段代码:
for char in s:
if ord(char) < 96 or ord(char) > 123:
s = s.replace(char, "")
它将删除....以外的所有字符Z是大写的。
对于只允许字符串中某些字符的相反要求,可以使用带有集补操作符[^ABCabc]的正则表达式。例如,要删除除ascii字母、数字和连字符以外的所有字符:
>>> import string
>>> import re
>>>
>>> phrase = ' There were "nine" (9) chick-peas in my pocket!!! '
>>> allow = string.letters + string.digits + '-'
>>> re.sub('[^%s]' % allow, '', phrase)
'Therewerenine9chick-peasinmypocket'
来自python正则表达式文档:
不在范围内的字符可以通过互补来匹配 一组。如果集合的第一个字符是'^',则所有字符 不在集合中的将被匹配。例如,[^5]将匹配 除'5'以外的任何字符,[^^]将匹配除 “^”。的第一个字符没有特殊意义 集。