1

How can I find and extract integers (without using the re module) from a list of strings and integers.

['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']

How do I extract all the integers (2,42,69) in form of a list? Desired output:

[2, 42, 69]

2 Answers2

1

One quick solution would be to try to cast the items to an int and keep those that succeed.

List of any type:

result = []
for i in x:
    try:
        result.append(int(i))
    except Exception:
        pass

print(result)
>>[2, 42, 69]

List Of Strings

As Mateen Ulhaq mentioned, if your input is always string type, it would be more appropriate to use:

[int(s) for s in my_list if s.isdigit()]

Note: This solution won't work if your string has negative numbers such as '-12'

user1767754
  • 23,311
  • 18
  • 141
  • 164
0

You can do this by iterating over every element of list and try to convert it into an integer. If you get successful in the conversion then append it to the list of integers.

a = ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']
ints = []
for i in a:
    try:
        z = int(i)
        ints.append(z)
    except:
        pass

Or you could go with a oneliner from here:

a = ['My', '2', 'favorite', 'numbers', 'are', '42', 'and', '69']
[int(s) for s in a if s.isdigit()]
#[2, 42, 69]
Ubdus Samad
  • 1,218
  • 1
  • 15
  • 27