0

Removing list's elements from string PYTHON

How can I remove all list's elements from string For example: list = ["1", "2", "3"] str = "random1 random2 random3" And I want it to become "random random random"

19th Sep 2021, 2:07 PM
Матвей Стаселько
Матвей Стаселько - avatar
8 Réponses
+ 4
Матвей Стаселько maybe you can do it this way, import re for i in list: str=re.sub(i,"",str) print(str) Just saying that you shouldn't use keywords like list as variables name .
19th Sep 2021, 2:20 PM
Abhay
Abhay - avatar
+ 2
Матвей Стаселько u can use variable.translate() Example : list = ['1', '2', '3'] str = "random1 random2 random3" newStr = str.translate({ord(x): '' for x in list}) print(newStr)
19th Sep 2021, 2:21 PM
Pariket Thakur
Pariket Thakur - avatar
+ 1
Матвей Стаселько i mean should it output "random" for something like "1random" or "ran1dom" ?
19th Sep 2021, 2:11 PM
Abhay
Abhay - avatar
+ 1
Abhay, Wait I was wrong, i want that result that you wrote
19th Sep 2021, 2:14 PM
Матвей Стаселько
Матвей Стаселько - avatar
0
And if it was "ran1dom" or "1random" instead of random1 ?
19th Sep 2021, 2:09 PM
Abhay
Abhay - avatar
0
Abhay, Yes
19th Sep 2021, 2:10 PM
Матвей Стаселько
Матвей Стаселько - avatar
0
Abhay, No, i just needed to remove all elements from the list
19th Sep 2021, 2:12 PM
Матвей Стаселько
Матвей Стаселько - avatar
0
Abhay, HrCoder Thanks! All yours solutions is what I need!
19th Sep 2021, 3:18 PM
Матвей Стаселько
Матвей Стаселько - avatar