Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

Can't seem to split a string in Python


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you declare that a function takes a positional argument, then you must supply that argument when calling the function.

As it is, your main() function does not require any argument so just change it to:

def main():
    last_letters('Ani,Trevor,Karen,Jasmine,Ryan')

Also, the argument name self is by convention used as a reference to an object instance within the object itself. You find it as the first argument to a method (a function that is bound to an instance of an object), whereas you are using standalone function.

The argument to last_letters() is the string 'Ani,Trevor,Karen,Jasmine,Ryan' when that function is called in main(). last_letters() does require the argument, but for the aforementioned reasons it should not be named self. You could just call it s or something descriptive of its value.

Finally the line last_letters1 = last_letters.split(",") won't work. You need to call split() on a string instance, like this:

def last_letters(text):
    names = text.split(",")
    # do something with names...
    # return a list containing the last letter of each name
    return [name[-1] for name in names]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...