11

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?

user1058492
  • 561
  • 2
  • 5
  • 9
  • 2
    Do I understand it correctly, that by `'%s' %(filename)` you are converting a string to string? If `filename` is a string, then just replace `'%s' %(filename)` with `filename`. – Tadeck Nov 22 '11 at 22:21
  • Adding to Tadeck's comment, if `filename` is not a string then `str(filename)` is equivalent to `'%s' % filename`. – Andrew Clark Nov 22 '11 at 22:23

5 Answers5

19

Use search instead of findall:

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

Alternatively:

number = filter(str.isdigit, filename)
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
  • 1
    Although `filter` is more similar to `re.findall` in cases where there are multiple groups of numbers e.g. using _"FILE-340-1.txt"_ `filter` produces _"3401"_ while `re.search` only returns the first group _"340"_. – Matthew Wilcoxson Jul 18 '13 at 11:45
2

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

numbers = int(re.search(r'\d+', filename).group())
Justin
  • 84,773
  • 49
  • 224
  • 367
ewegesin
  • 229
  • 3
  • 3
1

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

Oded BD
  • 2,788
  • 27
  • 30
1

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'
Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
0

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

>>>int('123')
123
akjoshi
  • 15,374
  • 13
  • 103
  • 121
ogama8
  • 999
  • 1
  • 6
  • 6