SOLUTION: Ok guys I ended up using the following. It involves regular expressions. This is what I was trying to get at.
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
This isn't very elegant, but it is extremely robust. It also always works based on the format of the files I'm using. Thank you @The2ndSon for suggesting regular expressions. That's what I had vaguely heard of once and couldn't quite remember.
Original Question
In Python, say I am opening a file. In this file there are certain strings that I want. These strings have the format
"My favorite chili was chili number NUM"
where NUM
is replaced by a natural number (a non-negative integer).
What is the best way to find lines containing this string, and store NUM
? I have some code laid out, but it seems like there should be a more elegant solution. Are there built-ins made specifically for this purpose? It seems very similar to other string formatting stuff that Python has built-ins for.
I am using Python 2.7
Here is my code so far:
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]))
IMPORTANT EDIT: There can be more than one number on each line, and the numbers I want are NOT always necessarily at the end. The whole chili thing was just an example.