繁体   English   中英

从字符串中删除特殊字符,而不是用空格替换它们

[英]remove special character from string, not replace them with space

我正在尝试从字符串中删除特殊字符。 所有可用的示例仅用空格替换它们。 但我想摆脱它们并保留字符串的顺序。 以下是我尝试过的一些代码

input_string = "abcd. efgh ijk L.M"
re.sub(r"[^a-zA-Z0-9]+",'',input_string).split(' '))) #approach 1
re.sub(r"[\W_]+",'',input_string).split(' '))) #approach 2

所需的 output 是

"abcd efgh ijk LM"

您可以用空字符替换每个特殊字符(不包括空格):

re.sub(r"[^a-zA-Z0-9 ]+", '', input_string)

您可以在插入符号( ^ )之后添加一个空格,如下所示

In [1]: re.sub(r"[^ a-zA-Z0-9]+",'',input_string)
#                  ^ space here
Out[1]: 'abcd efgh ijk LM'

如果您还想删除尾随或前导空格,您可以使用strip方法。

In [2]: '    Hello    '.strip()
Out[2]: 'Hello'

您可以使用 .replace() function。

not_wanted_char = [".", "*"]

your_string = "abcd. efgh ijk L.M"

for i in not_wanted_char:
    your_string = your_string.replace(i,"")
# initializing bad_chars_list
bad_chars = [';', ':', '!', "*"]
 
# initializing test string 
test_string = "he;ll*o w!or;ld !"
 
# printing original string 
print ("Original String : " + test_string)
 
# using replace() to 
# remove bad_chars 
for i in bad_chars :
    test_string = test_string.replace(i, '')
 
# printing resultant string 
print ("Resultant list is : " + str(test_string))

原始字符串:“he;ll*ow;or;ld !”

结果列表是:“hello world”

如果你想保留空格,那么下面的正则表达式会像一个魅力

import re
input_string = "abcd. efgh ijk L.M"
re.sub('[^ A-Za-z0-9]+', '', input_string)

它会产生这个字符串 - abcd efgh ijk LM

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM