Reputation: 373
It looked simple, "remove whitespace from a string in the list". But for some reason, my code didn't work.
new_list = []
channels = "KMP, PRIME"
channel = channels.split(",")
for each in channel:
re.sub(r'^[^a-zA-Z]*', ' ', each)
new_list.append(each)
I also tried lstrip/strip, but none worked. Why? If I "cheat" with the following code, it will work. I still want to get to the bottom of the problem. What should I change to make it right?
channel = channels.split(", ")
Upvotes: 0
Views: 67
Reputation: 12669
You can try this approach too:
print(list(map(lambda x:x.strip(),channels.split(','))))
output:
['KMP', 'PRIME']
Upvotes: 0
Reputation: 164643
Here is one way using a list comprehension and str.strip
.
Note it does not appear you require regex for this task.
channels = 'KMP, PRIME'
lst = [i.strip() for i in channels.split(',')]
# ['KMP', 'PRIME']
res = ','.join(lst)
# KMP,PRIME
Upvotes: 3
Reputation: 49784
From the (Docs):
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by ...
You need to keep the value retuned by .sub()
for each in channel:
new_list.append(re.sub(r'^[^a-zA-Z]*', ' ', each))
Upvotes: 1