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]

Mich
  • 3,188
  • 4
  • 37
  • 85

5 Answers5

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()))]
Nick
  • 138,499
  • 22
  • 57
  • 95
1

Following works:

import re
test = "ON45"
print(test)
print(str(list(map(int, re.findall(r'\d+', test)))))
Maxqueue
  • 2,194
  • 2
  • 23
  • 55
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

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]
blhsing
  • 91,368
  • 6
  • 71
  • 106
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.

EdvardM
  • 2,934
  • 1
  • 21
  • 20