I have a string "user@domain+12223334444" and I want to replace "+1" with space. How can I achieve it with str.replace command?

This string is in a column of dataframe. After running the below code, I am getting an error

patients_test["contact"] = patients_test["contact"].str.replace("+1", " ")

Error: nothing to repeat at position 0


Solution 1:

Make the + into [+] so it's a character class matching the character +, not a modifier to make the previous thing be repeated one-or-more times.

patients_test["contact"] = patients_test["contact"].str.replace("[+]1", " ")

You could also use "\\+1" or r"\+1", but I strongly advise the [+] approach as it works the same way no matter what kind of quoting context is being used.

Solution 2:

Pandas str.replace does a regular expression match / replace by default.

That complexity is not necessary here, use

patients_test["contact"] = patients_test["contact"].str.replace("+1", " ", regex=False)

To use exact text matching without using a regular expression.