我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
当前回答
>>> 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循环,但你确实需要单独检查每个字符。
您还可以使用函数来替换不同类型的正则表达式或使用列表的其他模式。这样,您就可以混合正则表达式、字符类和真正基本的文本模式。当您需要替换大量元素(如HTML元素)时,它非常有用。
*注意:适用于Python 3.x
import re # Regular expression library
def string_cleanup(x, notwanted):
for item in notwanted:
x = re.sub(item, '', x)
return x
line = "<title>My example: <strong>A text %very% $clean!!</strong></title>"
print("Uncleaned: ", line)
# Get rid of html elements
html_elements = ["<title>", "</title>", "<strong>", "</strong>"]
line = string_cleanup(line, html_elements)
print("1st clean: ", line)
# Get rid of special characters
special_chars = ["[!@#$]", "%"]
line = string_cleanup(line, special_chars)
print("2nd clean: ", line)
在函数string_cleanup中,它以字符串x和未修饰的列表作为参数。对于元素或模式列表中的每一项,如果需要替代品,就会进行替换。
输出:
Uncleaned: <title>My example: <strong>A text %very% $clean!!</strong></title>
1st clean: My example: A text %very% $clean!!
2nd clean: My example: A text very clean
line = line.translate(None, " ?.!/;:")
如果你想让你的字符串只允许使用ASCII码,你可以使用这段代码:
for char in s:
if ord(char) < 96 or ord(char) > 123:
s = s.replace(char, "")
它将删除....以外的所有字符Z是大写的。
这是我的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)