我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
我想在python中删除字符串中的字符:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
但我有很多字符必须删除。我想了一个清单
list = [',', '!', '.', ';'...]
但是如何使用列表来替换字符串中的字符呢?
当前回答
我认为这是足够简单和将做!
list = [",",",","!",";",":"] #the list goes on.....
theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
newString="" #the unwanted character free string
for i in range(len(TheString)):
if theString[i] in list:
newString += "" #concatenate an empty string.
else:
newString += theString[i]
这是一种方法。但是如果你厌倦了保留一个你想要删除的字符列表,你实际上可以通过使用你迭代的字符串的顺序号来做到这一点。订单号是该字符的ASCII值。0作为字符的ASCII码是48,小写z的ASCII码是122,所以:
theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
newString = ""
for i in range(len(theString)):
if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
newString += ""
else:
newString += theString[i]
其他回答
''.join(c for c in myString if not c in badTokens)
另一种使用regex的方法:
''.join(re.split(r'[.;!?,]', s))
我认为这是足够简单和将做!
list = [",",",","!",";",":"] #the list goes on.....
theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
newString="" #the unwanted character free string
for i in range(len(TheString)):
if theString[i] in list:
newString += "" #concatenate an empty string.
else:
newString += theString[i]
这是一种方法。但是如果你厌倦了保留一个你想要删除的字符列表,你实际上可以通过使用你迭代的字符串的顺序号来做到这一点。订单号是该字符的ASCII值。0作为字符的ASCII码是48,小写z的ASCII码是122,所以:
theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
newString = ""
for i in range(len(theString)):
if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
newString += ""
else:
newString += theString[i]
您可以使用翻译方法。
s.translate(None, '!.;,')
为什么不利用这个简单的函数:
def remove_characters(str, chars_list):
for char in chars_list:
str = str.replace(char, '')
return str
使用功能:
print(remove_characters('A.B!C?', ['.', '!', '?']))
输出:
ABC