0

I'm working in python 2.6 and I would like to take "gpmetisfile.txt.part.4" and return just the number 4. (Ordinarily I would just lop off and save the end value, but its length and arrangement may change in the future and I would rather be safe and just obtain the numbers, in order, from the string itself).

There was a question similar to mine in 2009, but the answers were conflicting.

Thanks in advance.

Ason
  • 509
  • 2
  • 9
  • 25

2 Answers2

3

The following does what your question answer says: removes everything but the numbers. Is that what you need?

In [1]: s = 'gpmetisfile.txt.part.4'

In [2]: import re

In [3]: re.sub('\D', '', s)
Out[3]: '4'

The reason why I ask is that, for instance, 'gpmetisfile.txt.06_2012.part.4' will become '0620124'.

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
  • This is exactly what I need. Only one number will appear in the string, ie now my file is "gpmetis.part.1205.txt". Thank you for checking. – Ason Jun 22 '12 at 18:06
3
>>> s = 'as!das42!fsd'
>>> ''.join(filter(str.isdigit, s))
'42'