0

I want to extract numbers contained in an alphanumeric strings. Please help me on this.

Example:

line = ["frame_117", "frame_11","frame_1207"]

Result:

[117, 11, 1207]
Nawin K Sharma
  • 704
  • 2
  • 6
  • 14

3 Answers3

2
import re
temp = []
lines = ["frame_117", "frame_11","frame_1207"]
for line in lines:
    num = re.search(r'-?\d+', line)
    temp.append(int(num.group(0)))

print(temp) # [117, 11, 1207]
mmr
  • 516
  • 11
  • 30
2

You can split with special character '_' like this:

numbers = []
line = ["frame_117", "frame_11","frame_1207"]
for item in line:
    number = int(item.split("_",1)[1])
    numbers.append(number)
print(numbers)
Dharman
  • 30,962
  • 25
  • 85
  • 135
kietle
  • 153
  • 6
1

Rationale

The first thing I see is that the names inside the list have a pattern. The string frame, an underscore _ and the string number: "frame_number".

Step-By-Step

With that in mind, you can:

  1. Loop through the list. We'll use a list comprehension.
  2. Get each item from the list (the names="frame_number" )
  3. Split them according to a separator (getting a sublist with ["frame", "number"])
  4. And then create a new list with the last items of each sublist
numbers = [x.split("_")[-1] for x in line]
['117', '11', '1207']

Solution

  1. But you need numbers and here you have a list of strings. We make one extra step and use int().
numbers = [int(x.split("_")[-1]) for x in line]
[117, 11, 1207]

This works only because we detected a pattern in the target name.

But what happens if you need to find all numbers in a random string? Or floats? Or Complex numbers? Or negative numbers?

That's a little bit more complex and out of scope of this answer. See How to extract numbers from a string in Python?

He3lixxx
  • 3,263
  • 1
  • 12
  • 31
Guzman Ojero
  • 2,812
  • 1
  • 20
  • 20