我的程式只提取字母,而不是整個單詞。
def first_word(sentence):
return sentence[0]
def second_word(sentence):
return sentence[1]
def last_word(sentence):
return sentence[-1]
if __name__ == "__main__":
sentence = "I want to learn python"
print(first_word(sentence))
print(second_word(sentence))
print(last_word(sentence))
上面示例中的輸出必須是:
I
want
python
uj5u.com熱心網友回復:
sentence.split() 將回傳由空格分隔的所有單詞的串列:
def first_word(sentence):
return sentence.split()[0]
def second_word(sentence):
return sentence.split()[1]
def last_word(sentence):
return sentence.split()[-1]
if __name__ == "__main__":
sentence = "I want to learn python"
print(first_word(sentence))
print(second_word(sentence))
print(last_word(sentence))
uj5u.com熱心網友回復:
使用str.split方法:
def first_word(sentence):
return sentence.split()[0] # <- HERE
def second_word(sentence):
return sentence.split()[1] # <- HERE
def last_word(sentence):
return sentence.split()[-1] # <- HERE
if __name__ == "__main__":
sentence = "I want to learn python"
print(first_word(sentence))
print(second_word(sentence))
print(last_word(sentence))
輸出:
I
want
python
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358002.html
