我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
当前回答
#!/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
其他回答
这是我的Python 2/3兼容版本。因为翻译api已经改变了。
def remove(str_, chars):
"""Removes each char in `chars` from `str_`.
Args:
str_: String to remove characters from
chars: String of to-be removed characters
Returns:
A copy of str_ with `chars` removed
Example:
remove("What?!?: darn;", " ?.!:;") => 'Whatdarn'
"""
try:
# Python2.x
return str_.translate(None, chars)
except TypeError:
# Python 3.x
table = {ord(char): None for char in chars}
return str_.translate(table)
>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if c not in '?:!/;' )
'abc#@efg12'
用re.sub正则表达式
从Python 3.5开始,可以使用正则表达式re.sub进行替换:
import re
re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)
例子
import re
line = 'Q: Do I write ;/.??? No!!!'
re.sub('\ |\?|\.|\!|\/|\;|\:', '', line)
'QDoIwriteNo'
解释
在正则表达式(regex)中,|是一个逻辑或,\转义可能是实际的正则表达式命令的空格和特殊字符。而sub代表替换,在这种情况下是空字符串”。
下面一个. .没有使用正则表达式的概念..
ipstring ="text with symbols!@#$^&*( ends here"
opstring=''
for i in ipstring:
if i.isalnum()==1 or i==' ':
opstring+=i
pass
print opstring
如果你想让你的字符串只允许使用ASCII码,你可以使用这段代码:
for char in s:
if ord(char) < 96 or ord(char) > 123:
s = s.replace(char, "")
它将删除....以外的所有字符Z是大写的。