Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to str.replace multiple different strings with the same replacement?

Tags:

python

I am trying to replace multiple different strings with the same string replace rule.

list_names = ['!sdf?', '!sdfds?', '!afsafsa?', '!afasf?']

for i in list_names:
    vari1 = list_names[1]
    vari2 = list_names[2]
    vari3 = list_names[3]

I am trying to replace the ! and the ? above with ''.

At the moment I can do this string by string using the below code:

list_names = ['!sdf?', '!sdfds?', '!afsafsa?', '!afasf?']
for i in list_names:
    vari1 = list_names[1]
    vari2 = list_names[2]
    vari3 = list_names[3]
    vari1 = vari1.replace('!', '').replace('?', '')
    vari2 = vari2.replace('!', '').replace('?', '')
    vari3 = vari3.replace('!', '').replace('?', '')

I am aware it doesn't make sense to use a loop in the above code. But I intend to build on this.

Given that the string replaces are the same for all 3 variables, is there any easy way to do this for all of them at once?

Thanks!

like image 566
johnJones901 Avatar asked Dec 05 '25 04:12

johnJones901


2 Answers

You can just use List-comprehension.

>>> [x.replace('!', '').replace('?','') for x in list_names]
['sdf', 'sdfds', 'afsafsa', 'afasf']

Also, if you have multiple strings to replace, you can even use regular expression combining them by | using re.sub function as mentioned below:

>>> import re
>>> [re.sub('\?|!', '', x) for x in list_names]
['sdf', 'sdfds', 'afsafsa', 'afasf']
like image 78
ThePyGuy Avatar answered Dec 07 '25 17:12

ThePyGuy


You are doing wrong code. You can simply iterate through the indices of the list and convert all of them just like below:

list_names = ['!sdf?', '!sdfds?', '!afsafsa?', '!afasf?']
for index in range(len(list_names)):
    list_names[index] = list_name[index].replace("!", '').replace('?', '')

how does range(len(list_names)) work?

first the length of list_names is calculated which in this case is 4. Now using range function we are able to get a list [0, 1, 2, 3] which are all the possible indices. By going through the list replacing each index we are able to update values.