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

前端 未结 5 2281
感动是毒
感动是毒 2021-02-20 02: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.f         


        
相关标签:
5条回答
  • 2021-02-20 02:32

    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'
    
    0 讨论(0)
  • 2021-02-20 02:43

    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

    0 讨论(0)
  • 2021-02-20 02:48

    Use search instead of findall:

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

    Alternatively:

    number = filter(str.isdigit, filename)
    
    0 讨论(0)
  • 2021-02-20 02:49

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

    >>>int('123')
    123
    
    0 讨论(0)
  • 2021-02-20 02:53

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

    numbers = int(re.search(r'\d+', filename).group())
    
    0 讨论(0)
提交回复
热议问题