I know how to use a dictionary as a switcher in Python. I'm not sure how to use one for my specific case. I think I will just need to use if, elif, and else but hopefully I am proved wrong by the community :)
I want to make a find/replace function for certain characters in strings. The string is at least one sentence but usually more and comprised of many words.
Basically what I am doing is the following:
if non-breaking hyphen in string: # string is a sentence with many words
replace non-breaking hyphen with dash
elif en dash in string:
replace en dash with dash
elif em dash in string:
replace em dash with dash
elif non-breaking space in string:
replace non-breaking space with space
.... and so forth
The only thing I can think of is splitting the string apart into separate sub-strings and then looping through them then the dictionary switcher would work. But this would obviously add a lot of extra processing time and the purpose of using a dictionary switcher is to save time.
I could not find anything on this specific topic searching everywhere.
Is there a way to use a switcher in Python using if in and elif in?
Here's the str.translate
solution
replacements = {
'\u2011': '-', # non breaking hyphen
'\u2013': '-', # en dash
'\u2014': '-', # em dash
'\u00A0': ' ', # nbsp
}
trans = str.maketrans(replacements)
new_string = your_string.translate(trans)
Note that this only works if you want to replace single characters from the input. {'a': 'bb'}
is a valid replacements
, but {'bb': 'a'}
is not.