[英]Python: Remove special character in string
I've the following string in python, example: 我在python中有以下字符串,例如:
"Peter North / John West"
Note that there are two spaces before and after the forward slash. 请注意,在正斜杠前后有两个空格。
What should I do such that I can clean it to become 我应该怎么做才能清洁它成为
"Peter North_John West"
I tried using regex but I am not exactly sure how. 我尝试使用正则表达式,但我不确定如何使用。 Should I use re.sub or pandas.replace?
我应该使用re.sub还是pandas.replace?
You can use 您可以使用
a = "Peter North / John West"
import re
a = re.sub(' +/ +','_',a)
Any number of spaces with slash followed by any number of slashes can be replaced by this pattern. 此模式可以替换任意数量的带斜杠的空格以及任意数量的斜杠。
In case of varying number of white spaces before and after /
: 如果在
/
之前和之后的空白数量不同,
import re
re.sub("\s+/\s+", "_", "Peter North / John West")
# Peter North_John West
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.