我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
当前回答
>>> s = 'a1b2c3'
>>> ''.join(c for c in s if c not in '123')
'abc'
其他回答
用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代表替换,在这种情况下是空字符串”。
在Python 3.5中
例如,
os.rename(file_name, file_name.translate({ord(c): None for c in '0123456789'}))
从字符串中删除所有数字
对于只允许字符串中某些字符的相反要求,可以使用带有集补操作符[^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'以外的任何字符,[^^]将匹配除 “^”。的第一个字符没有特殊意义 集。
#!/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
令我惊讶的是,还没有人推荐使用内置的过滤功能。
import operator
import string # only for the example you could use a custom string
s = "1212edjaq"
假设我们想过滤掉所有不是数字的东西。使用过滤器内置方法“…等效于生成器表达式(item for item在可迭代if函数(item)中)"[Python 3 Builtins: Filter]
sList = list(s)
intsList = list(string.digits)
obj = filter(lambda x: operator.contains(intsList, x), sList)))
在Python 3中返回
>> <filter object @ hex>
要得到打印的字符串,
nums = "".join(list(obj))
print(nums)
>> "1212"
我不确定过滤器在效率方面的排名,但在做列表理解等时,知道如何使用是一件好事。
更新
从逻辑上讲,既然过滤器可以工作,你也可以使用列表理解,从我所读到的,它应该更有效,因为lambdas是编程函数世界的华尔街对冲基金经理。另一个优点是它是一个单行程序,不需要任何导入。例如,使用上面定义的字符串's',
num = "".join([i for i in s if i.isdigit()])
就是这样。返回值将是原始字符串中所有数字组成的字符串。
如果你有一个特定的可接受/不可接受字符列表,你只需要调整列表理解的' If '部分。
target_chars = "".join([i for i in s if i in some_list])
或者,
target_chars = "".join([i for i in s if i not in some_list])