Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to insert special character in a string given a full list in Python?

I have a list that contains some strings that have ‘\’ in them.

Ex:

'PEOPLE\\S BANK', 'PRIME MINISTER\\S'

I would like to add a single quote after every string that contains a \ in them.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Ive tried

import re
tt = re.sub(r'(\\)', r'\1"', str(updated_unique_accts))

This just adds a " between each . Any thoughts? There are multiple strings that contain this pattern.

Desired output

'PEOPLE\\'S BANK', 'PRIME MINISTER\\'S'

>Solution :

You’re very close, you just need to remember that both ' and " can be used for strings in python:

for line in updated_unique_accts:
    tt = re.sub(r'(\\\\)', r"\1'", line)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading