Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple symbols using replace()

Tags:

python

replace

How can I replace multiple symbols with the method replace()? Is it possible to do that with just one replace()? Or is there any better ways?

The symbols can look like this for example -,+,/,',.,&.

like image 423
michael Mekonnen Avatar asked Jan 04 '23 22:01

michael Mekonnen


2 Answers

You can use re.sub and put the characters in a character class:

import re
re.sub('[-+/\'.&]', replace_with, input)
like image 151
Maroun Avatar answered Jan 19 '23 04:01

Maroun


You may do it using str.join with generator expression (without importing any library) as:

>>> symbols = '/-+*'
>>> replacewith = '.'
>>> my_text = '3 / 2 - 4 + 6 * 9'  # input string

#  replace char in string if symbol v
>>> ''.join(replacewith  if c in symbols else c for c in my_text)
'3 . 2 . 4 . 6 . 9'   # Output string with symbols replaced
like image 34
Moinuddin Quadri Avatar answered Jan 19 '23 05:01

Moinuddin Quadri