ELEMENTARY.02.Correct Sentence

任務:

For the input of your function will be given one sentence. You have to return its fixed copy in a way so it』s always starts with a capital letter and ends with a dot.

Pay attention to the fact that not all of the fixes is necessary. If a sentence already ends with a dot then adding another one will be a mistake.

Input: A string.

Output: A string.

Example:

correct_sentence("greetings, friends") == "Greetings, friends."ncorrect_sentence("Greetings, friends") == "Greetings, friends."ncorrect_sentence("Greetings, friends.") == "Greetings, friends."n


我的代碼:

def correct_sentence(text: str):n i = -1n if text[i] == .:n text = text.capitalize()n else:n while text[i].isalpha():n breakn else:n i -=1n text = text+.n text = text.capitalize()n return textn


大神們的代碼:

第一,Clear:

def correct_sentence(text: str) -> str:n """Corrected sentence starting with a capital letter, ending with a dot."""n return text.capitalize() + . * (not text.endswith(.))n

第二,Creative:

correct_sentence = lambda t: t.capitalize() + "." * (t[-1]!=".")n

第三,Speedy:

def correct_sentence(text: str) -> str:n """n returns a corrected sentence which starts with a capital lettern and ends with a dot.n """n # your code heren if(text.find(.) == -1):n text += .n return text.capitalize()n


我好像有個問題。不愛寫注釋。

以後的程序盡量爭取寫上。

推薦閱讀:

編程零基礎,如何學習Python?
在數學建模問題中,matlab和Python各自的特點有哪些?
函數內部的變數在函數執行完後就銷毀,為什麼可變對象卻能保存上次調用時的結果呢??
Python3.5.1中如何將input讀取的字元串改為數字?
Python中 a < b < c之類的語句到底是怎麼回事?

TAG:Python | Python入门 | Python3x |