我试图使用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'
其他回答
这个怎么样:
def text_cleanup(text):
new = ""
for i in text:
if i not in " ?.!/;:":
new += i
return new
>>> line = "abc#@!?efg12;:?"
>>> ''.join( c for c in line if c not in '?:!/;' )
'abc#@efg12'
你可以使用re模块的正则表达式替换。使用^表达式可以准确地从字符串中选择想要的内容。
import re
text = "This is absurd!"
text = re.sub("[^a-zA-Z]","",text) # Keeps only Alphabets
print(text)
输出结果将是“这是荒谬的”。只有在^符号之后指定的内容才会出现。
>>> s = 'a1b2c3'
>>> ''.join(c for c in s if c not in '123')
'abc'
我是不是错过了重点,或者仅仅是以下几点:
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"