【Python CheckiO 题解】First Word
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
題目描述
【First Word】:給定一個字符串,找到其中的第一個單詞(單詞非字母),輸入的字符串可能包含點和逗號,字符串可能以字母、點或空格開頭,單詞中可能包含撇號。
【鏈接】:https://py.checkio.org/mission/first-word/
【輸入】:字符串
【輸出】:字符串
【前提】:原字符串可能包含大小寫字母、空格、逗號、點(.)和撇號(')
【范例】:
first_word("Hello world") == "Hello" first_word("greetings, friends") == "greetings"解題思路
在本題中,給定的字符串只包含 . , ' 三種符號,而遇到 ' 是不用處理的,因此可以直接用 replace() 方法,將 . 和 , 替換成空格,然后再以空格為分隔符,將字符串進行切片,最后返回第一個元素即可。
代碼實現
def first_word(text: str) -> str:"""returns the first word in a given text."""# your code herereturn text.replace(',',' ').replace('.',' ').split( )[0]if __name__ == '__main__':print("Example:")print(first_word("Hello world"))# These "asserts" are used for self-checking and not for an auto-testingassert first_word("Hello world") == "Hello"assert first_word(" a word ") == "a"assert first_word("don't touch it") == "don't"assert first_word("greetings, friends") == "greetings"assert first_word("... and so on ...") == "and"assert first_word("hi") == "hi"assert first_word("Hello.World") == "Hello"print("Coding complete? Click 'Check' to earn cool rewards!")大神解答
大神解答 NO.1
def first_word(text: str) -> str:import rea = re.split("[^a-zA-Z']",text)output =""for i in a:output += iif output != "":return(output)大神解答 NO.2
def first_word(text: str) -> str:i=0j=0while i < len(text) and text[i].isalpha() == False:i+=1text1=text[i:]while j < len(text1) and text1[j]!='.' and text1[j]!=',' :j += 1s = text1[:j].split(' ')return s[0]大神解答 NO.3
import redef first_word(text: str) -> str:return re.findall(r"[A-Za-z']+", text)[0] 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【Python CheckiO 题解】First Word的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 目前安卓阵营最强CPU性能!天玑9000
- 下一篇: REVERSE-PRACTICE-CTF