【Python CheckiO 题解】Secret Message
CheckiO 是面向初學者和高級程序員的編碼游戲,使用 Python 和 JavaScript 解決棘手的挑戰和有趣的任務,從而提高你的編碼技能,本博客主要記錄自己用 Python 在闖關時的做題思路和實現代碼,同時也學習學習其他大神寫的代碼。
CheckiO 官網:https://checkio.org/
我的 CheckiO 主頁:https://py.checkio.org/user/TRHX/
CheckiO 題解系列專欄:https://itrhx.blog.csdn.net/category_9536424.html
CheckiO 所有題解源代碼:https://github.com/TRHX/Python-CheckiO-Exercise
題目描述
【Secret Message】:找到一個字符串中所有的大寫字母,返回結果為字符串形式,且大寫字母要按照原字符串中的順序排列。
【鏈接】:https://py.checkio.org/mission/secret-message/
【輸入】:一段文本(unicode)
【輸出】:所有大寫字母組成的字符串或者空字符串
【前提】: 0 < len(text) ≤ 1000
【范例】:
find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO" find_message("hello world!") == ""解題思路
直接利用 re 模塊的 findall 方法,提取原字符串中的所有大寫字母,然后再用 join() 方法將所有大寫字母轉換成字符串即可
代碼實現
import re def find_message(text: str) -> str:"""Find a secret message"""text = re.findall('[A-Z]', text)text = ''.join(text)return textif __name__ == '__main__':print('Example:')print(find_message("How are you? Eh, ok. Low or Lower? Ohhh."))#These "asserts" using only for self-checking and not necessary for auto-testingassert find_message("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO", "hello"assert find_message("hello world!") == "", "Nothing"assert find_message("HELLO WORLD!!!") == "HELLOWORLD", "Capitals"print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")大神解答
大神解答 NO.1
def find_message(text: str) -> str:"""Find a secret message"""return "".join(s for s in text if s.isupper()== True)大神解答 NO.2
def find_message(text: str) -> str:return ''.join(list(filter(lambda x: x.isupper(), text)))大神解答 NO.3
def find_message(text):"""Find a secret message"""message = ''for i in text:if i.isupper(): message +=ireturn message總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】Secret Message的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 有不良信用记录可以申请浦发万用随借金吗
- 下一篇: 定了!我国2025年底将关停标清频道 全