【问题标题】:How to extract 1st, 2nd and last words from the string using functions?如何使用函数从字符串中提取第一个、第二个和最后一个单词?
【发布时间】:2021-12-27 00:31:05
【问题描述】:
我的程序只提取字母,而不是整个单词。
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
【问题讨论】:
标签:
python
string
function
【解决方案1】:
使用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
【解决方案2】:
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))