在Python中,从字符串中获取未知int的最佳方法是什么?

时间:2014-07-22 17:54:21

标签: python string parsing search built-in

解决方案:好的我最后使用了以下内容。它涉及正则表达式。这就是我想要的。

matches = re.findall(r'My favorite chili was number \d+"', line) # gets 1 match
    if matches: # if there are matches
        nums.append(int(re.findall(r'\d+',matches[0])[0])) # append the number

这不是很优雅,但它非常强大。它总是根据我正在使用的文件的格式工作。感谢@ The2ndSon建议使用正则表达式。这就是我曾经模糊地听过的,并且不太记得。


原始问题

在Python中,我说我正在打开一个文件。在这个文件中有一些我想要的字符串。这些字符串的格式为

"My favorite chili was chili number NUM"

其中NUM被自然数(非负整数)替换。


查找包含此字符串的行的最佳方法是什么,并存储NUM?我有一些代码,但似乎应该有一个更优雅的解决方案。是否有专门为此目的制作的内置插件?它似乎与Python内置的其他字符串格式化内容非常相似。


我正在使用Python 2.7


到目前为止,这是我的代码:

nums = []
with open('file.txt', 'r') as txtfile:
    for line in txtfile:
        indx = line.find('My favorite chili was number ')
            if indx != -1:
                nums.append(int(line[indx+30:indx+31]))

重要编辑:每行可以有多个号码,我想要的号码并不总是在最后。整个辣椒只是一个例子。

2 个答案:

答案 0 :(得分:2)

您可以使用正则表达式从字符串中提取数字。

>>>import re
>>>re.findall(r'\d+', "My favorite chili was chili number 19")
['19']

答案 1 :(得分:1)

假设数字始终在最后,您可以这样做:

test = "My favorite chili was chili number 123456"

num = int(test.split()[-1])
print(num)
相关问题