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

Replace spaces in a locations but not as simple

I made a service to record some data from trains company. But over the past few months, they have modified the rules to save the names of train stations. For instance, there is both ‘Saint-Charles’ and ‘Saint – Charles’, so my requests are not complete in my database.
I would like to know if there is a quick (and safe) way to unify the both syntax? I would like to change ‘Saint – Charles’ to ‘Saint-Charles’ but I don’t really know how to do it safely. Indeed, I have other locations ‘Saint James’ and I don’t want to make a rule to replace the space in the word.
Maybe regex expression will help, but I am not familiar with this.

I use Python for my service.

Thank you for your help.

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

Regards,

>Solution :

my_str = "Saint - Charles"

converted_string = "-".join([substring.strip() for substring in my_str.split("-")])

print(converted_string)

Saint-Charles

How this works is we split the original string by "-", then we use .strip() function to trim out spaces both at the start and end of the substring, then finally joining the substrings back which results in spaces left and right of "-" being removed.

Strings without "-" like "Saint James" will be unaffected.

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