How do you slice a string using the output of a function?

时间:2018-07-25 05:21:19

标签: python python-3.x

I am a novice at Python. I am trying to use the output of 2 functions as the start and end values of a slice() method.

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 get the following error from PyLab:

Syntax error line 19: 
i=line[firstposition:secondposition]
TypeError:
slice indices must be integers or None or have an __index__ method

If the functions are returning integers, why will the slice not accept them? The .txt file used contains lines with words and an email address, with the goal being to index the start and finish of every domain.

2 个答案:

答案 0 :(得分:1)

You're trying to call firstposition and secondposition as though they are variables, rather than functions. If you call them as functions by adding () to each your code will work.

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

答案 1 :(得分:1)

You're not calling your functions inside the slice. To call the functions you need to put () after the function names.

i = line[firstposition():secondposition()]

Just using the function name is passing the function by name, sometimes called a "function pointer". It lets you pass functions into other functions so they can be called within. However, passing a function does not call that function.

Meanwhile, when you call a function with (), you're essentially replacing that spot where you called the function with the value that was returned from said function.