0

I looked online and every method for extracting numbers from strings uses the [int(word) for word in a_string.split() if word.isdigit()] method, however when I run the code below, it does not extract the number 45

test = "ON45"
print(test)
print([int(i) for i in test.split() if i.isdigit()])

This is what python prints

ON45
[]

The second list is empty, it should be [45] which I should be able to access as integer using output_int = test[0]

1
  • @busybear not a good dup because it also uses split but the way iit was supposed to be... Commented Apr 3, 2020 at 7:39

5 Answers 5

1

Following works:

import re
test = "ON45"
print(test)
print(str(list(map(int, re.findall(r'\d+', test)))))
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to get the individual digits

print([int(i) for i in test if i.isdigit()])

output [4, 5]

If you want to get concatenated numbers

import re
print(re.findall(r'[0-9]+', test))

output ['45']

hope it helps

Comments

1

str.split with no arguments splits a string on whitespace, which your string has none of. Thus you end up with i in your list comprehension being ON45 which does not pass isdigit(); hence your output list is empty. One way of achieving what you want is:

int(''.join(i for i in test if i.isdigit()))

Output:

45

You can put that in a list if desired by simply enclosing the int in [] i.e.

[int(''.join(i for i in test if i.isdigit()))]

Comments

0

You can iterate through the characters in each string from the list resulting from the split, filter out the non-digit characters, and then join the rest back into a string:

test = "ON45"
print([int(''.join(i for i in s if i.isdigit())) for s in test.split()])

This outputs:

[45]

Comments

0

Yes, because string.split() splits on space, which you don't have in the original string. With the string "ON 24" it'd work just fine.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.