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]
1
  • 2
    Try: [int(s.split('_')[-1]) for s in line] Commented May 29, 2021 at 12:49

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.