MRA
MRA

Reputation: 33

Search for a specific characters and filter

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

Answers (4)

bb1
bb1

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

Davinder Singh
Davinder Singh

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

talhasaleem09
talhasaleem09

Reputation: 246

You can replace these characters.

l2 = list(map(lambda x: int(x.replace('\n', '').replace('\t', '')), l1))

Upvotes: 0

SAI SANTOSH CHIRAG
SAI SANTOSH CHIRAG

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

Related Questions