Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple words with one word in python? [duplicate]

I have a few strings that may contain the abbreviation or the full name of something and I would like to replace them all to the same variation of the word.

For example,

"8 gigs", "8 gigabytes", and "8 gbs" should all change to "8 gigabytes"

What would be the best way to do this? Have a seperate replace for each of them?

Also I am trying to do this for more than one word (ie megabytes, terabytes) do each of those need a different replace or is there a way to put them all in one?

like image 641
jped Avatar asked Mar 29 '26 15:03

jped


1 Answers

A simple re.sub will do the trick for you.

>>> import re
>>> s = 'gigabytes, foo gigs; foo gbs'
>>> re.sub('(gigabytes|gigs|gbs)','gigabytes',s)
'gigabytes, foo gigabytes; foo gigabytes'
like image 72
Brien Avatar answered Mar 31 '26 03:03

Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!