Replace spaces in a locations but not as simple

Question:

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.

Regards,

Asked By: Fred

||

Answers:

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.

Answered By: piplup
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.