user1058492
user1058492

Reputation: 561

How do I find one number in a string in Python?

I have a file called something like FILE-1.txt or FILE-340.txt. I want to be able to get the number from the file name. I've found that I can use

numbers = re.findall(r'\d+', '%s' %(filename))

to get a list containing the number, and use numbers[0] to get the number itself as a string... But if I know it is just one number, it seems roundabout and unnecessary making a list to get it. Is there another way to do this?


Edit: Thanks! I guess now I have another question. Rather than getting a string, how do I get the integer?

Upvotes: 11

Views: 20301

Answers (5)

ogama8
ogama8

Reputation: 1019

In response to your new question you can cast the string to an int:

>>>int('123')
123

Upvotes: 0

ewegesin
ewegesin

Reputation: 329

Adding to F.J's comment, if you want an int, you can use:

numbers = int(re.search(r'\d+', filename).group())

Upvotes: 2

Facundo Casco
Facundo Casco

Reputation: 10605

Another way just for fun:

In [1]: fn = 'file-340.txt'

In [2]: ''.join(x for x in fn if x.isdigit())
Out[2]: '340'

Upvotes: 1

Oded BD
Oded BD

Reputation: 3286

If you want your program to be effective

use this:

num = filename.split("-")[1][:-4]

this will work only to the example that you showed

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208675

Use search instead of findall:

number = re.search(r'\d+', filename).group()

Alternatively:

number = filter(str.isdigit, filename)

Upvotes: 19

Related Questions