Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Str.replace('\\', '') not working for backslashes [closed]

Tags:

python

string

I want to remove backslashes and I've read that you can use

Str.replace('\\', '') 

I've also tried

re.sub(r'\\', '',text)

However both do not work for me. I'm wondering if someone can help me figure out what is wrong.

text = ['with General Atlantic, Newman\'s Own Foundation, The Pershing Square Foundation, Rockefeller Philanthropy Advisors, and Echoing Green announced a three-year partnership which will invest']
text.replace('\\','')

I still get 'Newman\'s Own Foundation'

To clarify: I'm attempting to get words with Consecutive words where first letters are capitalized, as in proper nouns. The backslash messes up this regex from capturing Newman's Own. So it seems like removing the backslash isn't the best idea? r'\b(?

I'm getting the backslashes when I print the text in ipython notebook

like image 724
user3314418 Avatar asked May 14 '26 16:05

user3314418


1 Answers

The text does not contain a backslash to remove. The backslash present in text actually escapes the apostrophe.

If you try print text[0] , you will get an output as:

with General Atlantic, Newman's Own Foundation, The Pershing Square Foundation, Rockefeller Philanthropy Advisors, and Echoing Green announced a three-year partnership which will invest

Which has no backslash.

The reason you get the backslash is probably because it returns the representation. [ probably since even python shell does not return the backslash unless you explicitly call the repr(text[0]) function, atleast not in your case. ].

Incase you want to remove that escaping backslash from the representation and convert it back to a string ( though I find it pointless to do so ) you can try this:

repr(text[0]).replace('\\','')[1:-1]

EDIT: When working with regex convert your r'some text' to str(r'some text'). That should work.

like image 177
Raghav RV Avatar answered May 17 '26 05:05

Raghav RV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!