【Python CheckiO 题解】Correct Sentence
CheckiO 是面向初學(xué)者和高級(jí)程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰(zhàn)和有趣的任務(wù),從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關(guān)時(shí)的做題思路和實(shí)現(xiàn)代碼,同時(shí)也學(xué)習(xí)學(xué)習(xí)其他大神寫(xiě)的代碼。
CheckiO 官網(wǎng):https://checkio.org/
我的 CheckiO 主頁(yè):https://py.checkio.org/user/TRHX/
CheckiO 題解系列專(zhuān)欄:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有題解源代碼:https://github.com/TRHX/Python-CheckiO-Exercise
題目描述
【Correct Sentence】:給定一個(gè)字符串,將其轉(zhuǎn)換成正確的句子:如果原字符串中,首字母是小寫(xiě),則將其轉(zhuǎn)換成大寫(xiě),句尾如果沒(méi)有句號(hào)(.),則要加個(gè)句號(hào),如果原字符串中,首字母是大寫(xiě),則新字符串中不變,如果句尾有句號(hào),則新字符串句尾也不變。
【鏈接】:https://py.checkio.org/mission/correct-sentence/
【輸入】:字符串
【輸出】:字符串
【前提】:原字符串中只包含 a-z A-Z , . 和空格
【范例】:
correct_sentence("greetings, friends") == "Greetings, friends." correct_sentence("Greetings, friends") == "Greetings, friends." correct_sentence("Greetings, friends.") == "Greetings, friends."解題思路
用 islower() 方法判斷第一個(gè)字母是否為小寫(xiě)字母,若是小寫(xiě)字母,則用 upper() 方法將其轉(zhuǎn)換成大寫(xiě)字母,利用切片 text[1:],將轉(zhuǎn)換后的第一個(gè)字母和剩下的字符拼接起來(lái),組成新的字符串。
用 text[-1] 獲取最后一個(gè)字符,如果最后一個(gè)字符不是 .,則在整個(gè)字符串后面加上 .
最后返回處理過(guò)后的新字符串即可
代碼實(shí)現(xiàn)
def correct_sentence(text: str) -> str:"""returns a corrected sentence which starts with a capital letterand ends with a dot."""if text[0].islower():text = text[0].upper() + text[1:]if text[-1] != '.':text += '.'return textif __name__ == '__main__':print("Example:")print(correct_sentence("greetings, friends"))# These "asserts" are used for self-checking and not for an auto-testingassert correct_sentence("greetings, friends") == "Greetings, friends."assert correct_sentence("Greetings, friends") == "Greetings, friends."assert correct_sentence("Greetings, friends.") == "Greetings, friends."assert correct_sentence("hi") == "Hi."assert correct_sentence("welcome to New York") == "Welcome to New York."print("Coding complete? Click 'Check' to earn cool rewards!")大神解答
大神解答 NO.1
correct_sentence=lambda s: (s[0].upper() if ~-s[0].isupper() else s[0])+s[1:]+('.' if s[-1]!='.' else '')大神解答 NO.2
return ((text[0].upper() + text[1:]) if (text[0].islower() == True) else text) + ("." if text[-1]!= "." else "")大神解答 NO.3
correct_sentence=lambda t:t[0].upper()+t[1:]+'.'*(t[-1]!='.')總結(jié)
以上是生活随笔為你收集整理的【Python CheckiO 题解】Correct Sentence的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 45km续航无压力:小米电动滑板车4 P
- 下一篇: 感受下!最新财富自由标准公布:需要670