user1718064
user1718064

Reputation: 475

Re.sub python- Replacing more items at the the same time

I have to substitute a range of accented characters in a string with the respective non accented letters. I was thinking of using re.sub but I have no clue of how to substitute more items (each one with a different item) at the same time. So to be clearer:

import re
re.sub(r'è|ù|ò|à','e,u,o,a',string). 

First of all is this allowed in Python so to avoid to make a separate line for each letter? Thanks!

Upvotes: 1

Views: 244

Answers (1)

Andrew Clark
Andrew Clark

Reputation: 208425

re.sub() can accept a function as the replacement, so you can do something like the following:

reps = dict(zip('èùòà', 'euoa'))
re.sub(r'è|ù|ò|à', lambda m: reps[m.group(0)], some_string)

Example:

>>> re.sub(r'è|ù|ò|à', lambda m: reps[m.group(0)], 'à ò ù è')
'a o u e'

Upvotes: 1

Related Questions