Reputation: 27
Let's say I have a text file of integers separated by spaces (eg 1 4 6 27 189...) and I have in my python code a variable (let's call it 'num'). What do I use if I want to read the text file to check if num is already included as an integer in the text file? Eg if num = 27, then it would return a positive because 27 is already in there. What I don't want, however, is let's say num = 18, it to return positive because of the 18 in 189. Thanks.
Upvotes: 0
Views: 644
Reputation: 36033
with open('file.txt') as f:
print(str(num) in f.read().split())
f.read()
is the string contents of the file.
f.read().split()
is a list of the numbers as strings. .split()
splits on spaces. Because they're strings, we convert num
to a string with str(num)
.
Upvotes: 4