User12345
User12345

Reputation: 5490

Special characters in Python string replace

I have a string in python I want to replace any special characters in that string.

I have done like below

col_name = 'AN*_Gen_**Air_&Outlet_$Temp'

reps = (('_&', ' '), ('*_', '('), ('_*', ')'), ('#_', '{'), ('_#', '}'), ('_##', ';'), ('_$', '.'),
        ('_$$', ','), ('_**', '='))

original_cols = reduce(lambda a, kv: a.replace(*kv), reps, col_name)

Output:

'AN(Gen)*Air Outlet.Temp'

Expected output:

'AN(Gen=Air Outlet.Temp'

Here I see that in the string _** is being first replaced by )* instead of = as _* in reps is )

What should I do to get the correct string?

Upvotes: 1

Views: 99

Answers (1)

Morse
Morse

Reputation: 9144

Put ('_**', '=') before ('*_', '(') as more characters match should be higher preference.

reps = (('_**', '='), ('_&', ' '), ('*_', '('), ('_*', ')'), ('#_', '{'), ('_#', '}'), ('_##', ';'), ('_$', '.'),
        ('_$$', ','))

Output

'AN(Gen=Air Outlet.Temp'

Upvotes: 2

Related Questions