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]
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]
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]
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"
.
With that in mind, you can:
"frame_number"
)"frame"
, "number"
])numbers = [x.split("_")[-1] for x in line]
['117', '11', '1207']
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?