Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

similar function to php's str_replace in python?

Tags:

python

is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string).

I know I can achieve this using for loops, but just looking more elegant way.

like image 240
Mohamed Avatar asked Sep 08 '09 00:09

Mohamed


People also ask

How do you replace all occurrences of a string in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you replace one character in a string in Python?

replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character).

How do you replace a value in Python?

replace() Parameters The replace() method can take maximum of 3 parameters: old - old substring you want to replace. new - new substring which will replace the old substring. count (optional) - the number of times you want to replace the old substring with the new substring.


1 Answers

I believe the answer is no.

I would specify your search/replace strings in a list, and the iterate over it:

edits = [(search0, replace0), (search1, replace1), (search2, replace2)] # etc.
for search, replace in edits:
    s = s.replace(search, replace)

Even if python did have a str_replace-style function, I think I would still separate out my search/replace strings as a list, so really this is only taking one extra line of code.

Finally, this is a programming language after all. If it doesn't supply the function you want, you can always define it yourself.

like image 92
John Fouhy Avatar answered Sep 23 '22 05:09

John Fouhy