简体   繁体   English

Python:删除字符串中的特殊字符

[英]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.

相关问题 Python /从字符串中删除特殊字符 - Python / Remove special character from string 如何在Python中删除字符串末尾带有特殊字符的行 - How to remove rows with special character at the end of string in Python 如何:在Python中删除特殊字符后的部分Unicode字符串 - How to: remove part of a Unicode string in Python following a special character 如何在不删除空格的情况下删除 python 字符串中的特殊字符“^” - How to remove the special character '^' in a python string without removing whitespace with it 删除scrapy python中的特殊字符 - remove special character in scrapy python 在字符串中使用python'\\'特殊字符操作 - operate with python '\' special character in a string PYTHON-将特殊字符转换为字符串 - PYTHON - convert special character to string 尝试在python 2.7 TypeError中删除Unicode特殊字符时出错:预期为字符串或其他字符缓冲区对象 - Error while try to remove Unicode special character in python 2.7 TypeError: expected a string or other character buffer object 从 Python 的值集中删除特殊字符 - Remove special character from set of values in Python 使用python中的re.sub函数删除字符串中的特殊字符和撇号以及多余的空格 - Remove special character and apostrophe and unwanted space in string using re.sub function in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM