《笨辦法學python》習題25 筆記

2021-08-28 08:23:15 字數 2048 閱讀 6567

原文習題

def break_words(stuff):

"""this function will break up words for us """

words = stuff.split(' ')

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 sentense."""

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)

筆記:

split()通過指定分隔符對字串進行切片,如果引數 num 有指定值,則僅分隔 num 個子字串

str.split(str="", num=string.count(str)).
str – 分隔符,預設為所有的空字元,包括空格、換行(\n)、製表符(\t)等。

num – 分割次數。

例如:1.

str = "line1-abcdef \nline2-abc \nline4-abcd";

print (str.split(' ', 1 )

結果:

python ex0.py

['line1-abcdef', '\nline2-abc \nline4-abcd']

str = "line1-abcdef \nline2-abc \nline4-abcd";

print (str.split(' ', 2 )

結果:

python ex0.py

['line1-abcdef', '\nline2-abc', '\nline4-abcd']

pop()函式用於移除列表中的乙個元素(預設最後乙個元素),並且返回該元素的值。

sorted()函式對所有可迭代的物件進行排序操作。

>>>a = [5,7,6,3,4,1,2]

>>> b = sorted(a) # 保留原列表

>>> a

[5, 7, 6, 3, 4, 1, 2]

>>> b

[1, 2, 3, 4, 5, 6, 7]

笨辦法學python 習題32 筆記

for迴圈 for 變數 in列表 過程例如 for x in cla 迴圈語句for 自定義的x拿來迴圈獲得cla裡面的值 range 的用法 range stop range start,stop step start 計數從 start 開始。預設是從 0 開始。例如range 5 等價於ra...

笨辦法學python習題40 筆記

開頭便出現了兩處錯誤 typeerror song takes no arguments def init self,lyrics 第一處是 init 寫成了 int 第二處是雙下劃線 寫成了單下劃線 1.類 class 類就是乙個模板,用於生成例項的記憶體空間。2.例項 類的具體存在 類的例項化中...

笨辦法學python 習題25 更多更多練習

原始碼 命名函式 def break words stuff this function will break up words for us.設定變數words 使用.split 命令分割字串 words stuff.split 返回return words def sort words word...