Py学习  »  Python

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

Jicheo • 5 年前 • 1794 次点击  

我在python中有以下字符串,例如:

"Peter North  /  John West"

注意,正斜杠前后有两个空格。

我该怎么做才能把它洗干净

"Peter North_John West"

我试过用regex,但我不确定怎么用。 我应该使用re.sub还是pandas.replace?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40628
 
1794 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Chris
Reply   •   1 楼
Chris    6 年前

前后空格数不同时 / :

import re

re.sub("\s+/\s+", "_", "Peter North  /  John West")
# Peter North_John West
anky_91
Reply   •   2 楼
anky_91    6 年前

你可以使用

a = "Peter North  /  John West"
import re
a = re.sub(' +/ +','_',a)

这个模式可以替换带有斜杠和任意斜杠的任意数量的空格。