Home > Software engineering >  Can I extract only integers from each line in a string and save them in a list?
Can I extract only integers from each line in a string and save them in a list?

Time:09-17

I have a string containing 3 lines that looks like this.

@ 544 000
* 600 0007000...

I want to extract these numbers to a list as integers.

Numbers = [544000, 600000, 7000]

I've tried using a for loop splitting the data like this.

numbers = []    
for word in data.split():
    if word.isdigit():
        numbers.append(int(word))
print(numbers)

But the results were

[544, 0, 600, 0]

am I on the right track here,or do I need to split it some other way?

CodePudding user response:

You can use str.isdigit() str.join() (extract every character from the line and check it with str.isdigit(). Join every digit afterwards with str.join()):

s = """@ 544 000
* 600 000
‘7000..."""

for line in s.splitlines():
    print("".join(ch for ch in line if ch.isdigit()))

Prints:

544000
600000
7000

Or as a list:

numbers = [
    int("".join(ch for ch in line if ch.isdigit())) for line in s.splitlines()
]

EDIT: With added checks for lines not containing numbers:

numbers = [
    int(m)
    for line in s.splitlines()
    if (m := "".join(ch for ch in line if ch.isdigit())).isnumeric()
]

CodePudding user response:

The same as @AndrejKesely with a regex:

import re

numbers = [int(''.join(re.findall(r'(\d )', line))) for line in text.splitlines()]

Output:

>>> numbers
[544000, 600000, 7000]
  • Related