Can anyone tell me if there is any function for replacing multiples substrings within a string.
For instance we have this function call to replace multiple appearances of the same substring:

newLine = line.replace(';', '_')

Here I replace all appearances of ';' with '_'
But what I need is a function that receives a list of substrings to replace withing a string.

newLine = line.replace([';', ',', '.'], '_')

Here I replace all appearances of ';', ',' and '.' with '_'

regards,
bc.

Recommended Answers

All 5 Replies

I don't know if there's a specific function to do it, but you could do a simple for loop like:

>>> l = 'hi;your,face.is;on,fire'
>>> for c in [';',',','.']:
...     l = l.replace( c, '_' )
...     
>>> l
'hi_your_face_is_on_fire'
>>>

Or roll your own little function ie,

>>> l = 'hi;your,face.is;on,fire'
>>> def replaces( inp, old, new ):
...     for c in old: inp = inp.replace( c, new )
...     return inp
...     
>>> l = replaces(l, ';,.', '_')
>>> l
'hi_your_face_is_on_fire'
>>>

Same function, using list instead of string of chars

>>> l = 'hi;your,face.is;on,fire'
>>> l = replaces(l, [ ';', ',', '.' ], '_')
>>> l
'hi_your_face_is_on_fire'
>>>

You can use regexp (re module) instead of string module for that.

If you don't mind learning regex, which is almost another language, but used by many popular computer languages for text manipulation:

import re

p = re.compile(r'[;,.]')
s = 'hi;your,face.is;on,fire'
print p.sub('_', s)  # hi_your_face_is_on_fire

If you don't mind learning regex, which is almost another language

Regex it is just that, regular expression. A pattern describing some text.

Regex it is just that, regular expression. A pattern describing some text.

Yes we know! How about learning some Python first before giving primitive lectures. We are trying to help people and keep a friendly atmosphere here!

BTW, if you need help with the module re, simply type help(re). Or go to this Python expert:
http://www.amk.ca/python/howto/regex/

commented: What it is the matter with you. Where's the unfriendliness? -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.