file.read()输出字符串位置



我不知道如何拼写标题,但代码是:

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')

下面是blah.txt:

text,textagain,textbleh

如果在文件中找到用户输入,是否有方法也输出用户输入的字符串的位置?例如,如果用户输入"textagain",是否有方法输出"2",因为字符串"textagaon"位于文件中的第二个位置?

提前谢谢。

@Amiga500所说的可能会引起一些争论,我建议你分开。

"text,textagain,textbleh".split(",")将返回['text', 'textagain', 'textbleh'],此时您可以执行.index(your_word)并返回索引(1表示文本,因为Python使用基于零的索引,它是第二个条目(。

所以最后的代码可能是:

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')

试试这个:

行索引(物料(

if stuff in line:
posit = line.index(stuff)

如果你尝试直接跳到索引,但它不在那里,它会抛出一个错误。你可以使用一个尝试,除非作为一个变通方法,但它很难看。

啊,对不起,误读了。您有一个csv文件。

使用python中的csv阅读器在中读取

Python导入csv以列出

然后循环通过(假设行是每行的子列表(:

if stuff in line:
posit = line.index(stuff)