Home > database >  How to extract numbers from list of strings
How to extract numbers from list of strings

Time:08-20

List1 = ["rob12is34","jimmy56is78"]

I want output as

Output = ["1234","5678"]

If you gave an answer then please explain it

CodePudding user response:

Since its a list, loop the list first:

for item in List1:
    item

Then find all the numbers from it. To do it, loop the string and find all the digits from it.

output = []
from item in List1:
    digit_string = ''
    for character in item:
        if character.isdigit():
            digit_string  = character

    # Then add the digit_string to your list
    output.append(digit_string)
print(output)

CodePudding user response:

With a regex and re.sub:

List1 = ["rob12is34","jimmy56is78"]

import re

out = [re.sub(r'\D', '', s) for s in List1]

output: ['1234', '5678']

CodePudding user response:

for item in List1:
    print("".join([x for x in item if x in "0123456789"]))

CodePudding user response:

If you could use Regex

import re

List1 = ["rob12is34","jimmy56is78"]
for s in List1:
    print(''.join(re.findall('\d ', s)))

1234
5678

CodePudding user response:

using filter:

List1 = ["rob12is34", "jimmy56is78"]
result = []
for i in List1:
   result.append(''.join(filter(str.isdigit, i)))

print(result)
>>>> ['1234', '5678']
  • Related