我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
我试图使用Python从字符串中删除特定字符。这是我现在使用的代码。不幸的是,它似乎对字符串没有做任何事情。
for char in line:
if char in " ?.!/;:":
line.replace(char,'')
我如何正确地做到这一点?
当前回答
你可以使用re模块的正则表达式替换。使用^表达式可以准确地从字符串中选择想要的内容。
import re
text = "This is absurd!"
text = re.sub("[^a-zA-Z]","",text) # Keeps only Alphabets
print(text)
输出结果将是“这是荒谬的”。只有在^符号之后指定的内容才会出现。
其他回答
在Python 3.5中
例如,
os.rename(file_name, file_name.translate({ord(c): None for c in '0123456789'}))
从字符串中删除所有数字
line = line.translate(None, " ?.!/;:")
我是不是错过了重点,或者仅仅是以下几点:
string = "ab1cd1ef"
string = string.replace("1", "")
print(string)
# result: "abcdef"
把它放入循环:
a = "a!b@c#d$"
b = "!@#$"
for char in b:
a = a.replace(char, "")
print(a)
# result: "abcd"
使用过滤器,你只需要一行
line = filter(lambda char: char not in " ?.!/;:", line)
这将字符串视为可迭代对象,如果lambda返回True,则检查每个字符:
> > >帮助(过滤器) 模块__builtin__中内置函数过滤器的帮助: 过滤器(…) filter(function或None, sequence) ->列表、元组或字符串 返回函数(item)为true的序列项。如果 函数为None,返回为true的项。If sequence是一个元组 或者字符串,返回相同的类型,否则返回一个列表。
您还可以使用函数来替换不同类型的正则表达式或使用列表的其他模式。这样,您就可以混合正则表达式、字符类和真正基本的文本模式。当您需要替换大量元素(如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