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

2020-07-05 05:23发布

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?

标签: python string
5条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-05 05:46

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

>>>int('123')
123
查看更多
Evening l夕情丶
3楼-- · 2020-07-05 05:51

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

查看更多
来,给爷笑一个
4楼-- · 2020-07-05 06:01

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'
查看更多
对你真心纯属浪费
5楼-- · 2020-07-05 06:07

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

numbers = int(re.search(r'\d+', filename).group())
查看更多
▲ chillily
6楼-- · 2020-07-05 06:08

Use search instead of findall:

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

Alternatively:

number = filter(str.isdigit, filename)
查看更多
登录 后发表回答