简体   繁体   中英

Why isn't my str.replace() replacing this string?

I am simply trying to remove the string 'co ' (with space after 'co') from a pandas series:

x = pd.DataFrame({'string':['co hello', 'co hello','co hello', 'co hello', 'co hello']})

print(x)

     string
0  co hello
1  co hello
2  co hello
3  co hello
4  co hello

Applying str.replace() and recording result to new column string_clean :

x['string_clean']=(x['string'].str.replace('Co ', '', case=False,regex=False))
print(x)

     string string_clean
0  co hello     co hello
1  co hello     co hello
2  co hello     co hello
3  co hello     co hello
4  co hello     co hello

The co is not removed.

You can omit regex=False , because in Series.str.replace is default regex=True for substring replacement:

x['string_clean']= x['string'].str.replace('Co ', '', case=False)
print (x)
     string string_clean
0  co hello        hello
1  co hello        hello
2  co hello        hello
3  co hello        hello
4  co hello        hello

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM