Jicheo
Jicheo

Reputation: 1

Python: Remove special character in string

I've the following string in python, example:

"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?

Upvotes: 0

Views: 120

Answers (2)

Yoshitha Penaganti
Yoshitha Penaganti

Reputation: 464

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.

Upvotes: 1

Chris
Chris

Reputation: 29742

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

Upvotes: 0

Related Questions