0
How to use re.sub on lists? Is it possible?
a = ['bdf', 1, 2] a = re.sub('\d+', '', a[a:]) Above code giving error. TypeError: expected string or bytes-like object
5 Réponses
+ 6
No, you can't.
There are various ways to remove all ints from a list.
E.g. Using filter:
a = [*filter(lambda x: type(x) != int, a)]
But what do you want to do? It's not clear. Please give more details and help us help you.
+ 3
How to use re.sub on lists? Is it possible?
a = ['bdf', 1, 2]
a = [s for s in a if s.isalpha()]
+ 3
You should review the regular expressions("re") module of Python tutorial.
https://www.sololearn.com/learn/Python/2475
I recommend you to go through the comment section of each lesson too.
sub, as many other "re" methods is used to manipulate strings, NOT LISTS.
"""
re.sub(pattern, repl, string, count=0)
...
This method replaces all occurrences of the pattern in string with repl, substituting all occurrences, unless count provided. This method returns the modified string.
""" ---CopyPasted from Python tutorial.
By the way Oma Falk. Your code is showing me error for non-string types.
+ 1
Thanks Kevin
0
But what do you want to do? It's not clear. Please give more details and help us help you.
Just want to know if re.sub is usable in lists. Thats it. Want to understand re.sub