Home > database >  I have a string "user@domain 12223334444" and I want to replace " 1" with space.
I have a string "user@domain 12223334444" and I want to replace " 1" with space.

Time:01-17

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

CodePudding user response:

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.

CodePudding user response:

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.

  •  Tags:  
  • Related