Python 如何使用函数的输出对字符串进行切片?
我是Python的新手。我试图使用2个函数的输出作为slice()方法的起始值和结束值 我从PyLab得到以下错误:Python 如何使用函数的输出对字符串进行切片?,python,python-3.x,Python,Python 3.x,我是Python的新手。我试图使用2个函数的输出作为slice()方法的起始值和结束值 我从PyLab得到以下错误: Syntax error line 19: i=line[firstposition:secondposition] TypeError: slice indices must be integers or None or have an __index__ method 如果函数返回整数,为什么切片不接受它们?所使用的.txt文件包含带有单词和电子邮件地址的行,目的是为每个
Syntax error line 19:
i=line[firstposition:secondposition]
TypeError:
slice indices must be integers or None or have an __index__ method
如果函数返回整数,为什么切片不接受它们?所使用的.txt文件包含带有单词和电子邮件地址的行,目的是为每个域的开始和结束编制索引。您试图调用
firstposition
和secondposition
,就好像它们是变量而不是函数一样。如果通过向每个函数添加()
将它们作为函数调用,则代码将正常工作
file=open("../dataFiles/mbox-short.txt", mode='r')
line=file.readline()
def firstposition ():
return int(line.find("@"))
def secondposition ():
return int(line.find(" ", firstposition()))
while line != "":
i=line[firstposition():secondposition()]
print(i)
line = file.readline()
file.close()
您试图调用
firstposition
和secondposition
,就好像它们是变量而不是函数一样。如果通过向每个函数添加()
将它们作为函数调用,则代码将正常工作
file=open("../dataFiles/mbox-short.txt", mode='r')
line=file.readline()
def firstposition ():
return int(line.find("@"))
def secondposition ():
return int(line.find(" ", firstposition()))
while line != "":
i=line[firstposition():secondposition()]
print(i)
line = file.readline()
file.close()
您没有在片内调用函数。要调用函数,需要在函数名后面加上
()
i = line[firstposition():secondposition()]
仅使用函数名就是按名称传递函数,有时称为“函数指针”。它允许您将函数传递到其他函数中,以便可以在其中调用它们。但是,传递函数不会调用该函数
同时,当您使用
()
调用函数时,实际上是将调用函数的位置替换为从该函数返回的值。您不是在片内调用函数。要调用函数,需要在函数名后面加上()
i = line[firstposition():secondposition()]
仅使用函数名就是按名称传递函数,有时称为“函数指针”。它允许您将函数传递到其他函数中,以便可以在其中调用它们。但是,传递函数不会调用该函数
同时,当您使用
()
调用函数时,实际上是将调用函数的位置替换为从该函数返回的值。更改为i=line[firstposition():secondposition()]
更改为i=line[firstposition():secondposition()]