学习要点

  • Python split() 通过指定分隔符对字符串进行切片,分割成N个字符串数组
  • words.pop(0) 取数组中首个元素
  • words.pop(-1) 取数组中最后一个元素

程序代码

def break_words(stuff):
    """This fuction will break up words for us."""
    words = stuff.split(' ')  #通过指定分隔符对字符串进行切片,分割成N个字符串数组
    return words

def sort_words(words):
    """Sorts the words."""
    return sorted(words)

def print_first_word(words):
    """Prints the first word after popping it off."""
    word = words.pop(0)  #取数组中首个元素
    print(word)

def print_last_word(words):
    """Prints the last word after popping it off."""
    word = words.pop(-1) #取数组中最后一个元素
    print(word)

def sort_sentence(sentence):
    """Takes in a full sentence and returns the sorted words."""
    words = break_words(sentence)
    return sort_words(words)

def print_first_and_last(sentence):
    """Prints the first and last words of the sentence."""
    words = break_words(sentence)
    print_first_word(words)
    print_last_word(words)

def print_first_and_last_sorted(sentence):
    """Sorts the words then prints the first and last one."""
    words = sort_sentence(sentence)
    print_first_word(words)
    print_last_word(words)

模块调用 输出结果


PS D:\lpthw> python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)
>>> words
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
>>> sort_words = ex25.sort_words(words)
>>> sort_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_word(words)
All
>>> ex25.print_last_word(words)
wait.
>>> words
['good', 'things', 'come', 'to', 'those', 'who']
>>> ex25.print_first_word(sort_words)
All
>>> ex25.print_last_word(sort_words)
who
>>> sort_words
['come', 'good', 'things', 'those', 'to', 'wait.']
>>> sort_words = ex25.sort_sentence(sentence)
>>> sort_words
['All', 'come', 'good', 'things', 'those', 'to', 'wait.', 'who']
>>> ex25.print_first_and_last(sentence)
All
wait.
>>> ex25.print_first_and_last_sorted(sentence)
All
who
>>>
最后修改:2021 年 03 月 28 日
如果觉得我的文章对你有用,请随意赞赏