ELEMENTARY.03.First Word
You are given a string where you have to find its first word.
When solving a task pay attention to the following points:
- There can be dots and commas in a string.
- A string can start with a letter or, for example, a dot or space.
- A word can contain an apostrophe and its a part of a word.
- The whole text can be represented with one word and thats it.
Input: A string.
Output: A string.
Example:
first_word("Hello world") == "Hello"nfirst_word("greetings, friends") == "greetings"n
我的代碼:
def first_word(text: str) -> str:n s = n #將text最左側的非大小寫字元刪掉n for i in text:n if ord(i) not in range(65,91) and ord(i) not in range(97,123):n text = text.lstrip(i)n else:n breakn #將新text最左側的大小寫字元逐步加入到s字元串變數中,直到非字元出現n for i in text:n if ord(i) in range(65,91) or ord(i) in range(97,123) or ord(i) is 39:n s = s + in else:n breakn return sn
大神們的:
第一個,Clear:
import rendef first_word(text: str) -> str:n return re.search("([w]+)", text).group(1)n
第二個,Creative:
first_word = lambda t: .join([x, ][x in .,] for x in t).split()[0]n
第三個,Speedy:
import rendef first_word(text: str) -> str:n """n returns the first word in a given text.n """n # your code heren #return text.split(" ")[0]n return re.findall(r"[w]+", text)[0]n
我發現,在完成elementary island上的任務後,最佳答案都要在交錢後才能看,否則就要等上2個小時以後才能看。挺好!
這個問題,我開始的時候也想用正則表達式來完成。但是思維遇到障礙了。隧放棄。改用傳統的面相過程思路。
完成了,等上兩個小時就能看最佳答案了。
第一和第三都是用的正則。第二個用lambda函數。這個問題我認為解決的非常精彩。
大家覺得呢?
推薦閱讀: