Reputation: 33
I get a list from a source where some elements of lists are appended with newline and tab.
Those escape characters have to be removed from the list.
For ex. "l1" is a list which come from a different source.
l1=["12358\n\t\t", "69874\n\t\t\t\t", "25476\n\t"]
The desired list is l2.
l2=[12358,69874,25476]
I tried using regular expression to do that but unsuccessful.
Can anybody help me to get the result as "l2"?
Upvotes: 0
Views: 56
Reputation: 7873
This perhaps?
l1=["12358\n\t\t", "69874\n\t\t\t\t", "25476\n\t"]
[int(x) for x in l1]
It gives:
[12358, 69874, 25476]
Upvotes: 0
Reputation: 2162
Check out this code:
import re
regobj = re.compile(r'\d+')
l1=["12358\n\t\t", "69874\n\t\t\t\t", "25476\n\t"]
li = [int(regobj.search(i).group()) for i in l1]
print(li)
Upvotes: 0
Reputation: 246
You can replace these characters.
l2 = list(map(lambda x: int(x.replace('\n', '').replace('\t', '')), l1))
Upvotes: 0
Reputation: 2084
You can use .replace()
to remove characters at the end then use int()
to typecast string to integers
l2 = []
for i in range(len(l1)):
l1[i] = l1[i].replace('\n','').replace('\t','')
l2.append(int(l1[i]))
If there are any other characters, they can be also replaced in the similar manner.
Upvotes: 1