Reputation: 21
I didnt know how to word the title, but here's the code:
file = open('blah.txt', 'r')
line = file.read()
file.close()
stuff = input('enter stuff here')
if stuff in line:
print('its in the file')
else:
print('its not in the file')
and here's blah.txt:
text,textagain,textbleh
If the user input is found in the file, is there a way to also output the position of the string entered by the user? For example, if the user entered 'textagain', is there a way to output '2' because the string 'textagain' is in the second position in the file?
Thank you in advance.
Upvotes: 0
Views: 78
Reputation: 1145
What @Amiga500 said would likely work with some wrangling, I suggest splitting your strings up.
"text,textagain,textbleh".split(",")
would return ['text', 'textagain', 'textbleh']
at which point you can do .index(your_word)
and get back the index (1 for textagain since Python uses zero based indexing and it is the second entry).
So the final code might be:
file = open('blah.txt', 'r')
line = file.read()
file.close()
stuff = input('enter stuff here')
if stuff in line.split(","):
print('its in the file')
else:
print('its not in the file')
Upvotes: 2
Reputation: 1275
Try this:
line.index(stuff)
i.e.
if stuff in line:
posit = line.index(stuff)
If you try jumping straight to the index and its not there, it'll throw an error. You could use a try except as a workaround, but its ugly.
Ah, sorry, misread. You've a csv file.
Use the csv reader in python to read it in:
Then loop through (assuming line is the sub-list for each line):
if stuff in line:
posit = line.index(stuff)
Upvotes: 0