我的朋友給我發了一張截圖,一個他被困在評估中的問題,并問我是否能提供幫助。所以我試了一下,現在已經兩天了,這一直困擾著我的夢想。
問題:“創建一個名為 first_word 的函式,它接受一個字串并回傳第一個單詞。
給定代碼:
assert first_word("Random string here") == "Random"
assert first_word("Another random string here") == "Another"
assert first_word("Again a random string... etc.") == "Again"
print("Excerscise is complete"
我在其他變體中嘗試過的內容:
def first_word(x):
print(first_word.split().pop(0))
return first_word
assert first_word("Random string here") == "Random"
assert first_word("Another random string here") == "Another"
assert first_word("Again a random string... etc.") == "Again"
print("Excerscise is complete"
def first_word(x):
print(first_word.split()
return
assert first_word("Random string here") == "Random"
assert first_word("Another random string here") == "Another"
assert first_word("Again a random string... etc.") == "Again"
print("Excerscise is complete"
我嘗試了很多不同的組合,但想不出把它們都加起來,我在網上查了一下,我似乎無法讓代碼按照評估的方式作業。我可以回傳第一個字母,但我無法思考如何獲得第一個單詞。
我朋友做的這個評估對我沒有實際影響,而且已經通過了,所以他不會從中獲得任何收益。我只想了解如何完成這項任務,這將幫助我找出失敗的原因。
我目前在 eDiscovery 作業,并正在努力獲得我的安全性 和 OSCP。我覺得獲得任何有關 python 的知識都是有益的。任何幫助,將不勝感激。非常感謝
-Oerml
uj5u.com熱心網友回復:
您在這里有正確的基本想法:
def first_word(x):
print(first_word.split().pop(0))
return first_word
但對語法感到困惑:
first_word是function,并且是您嘗試獲取的第一個單詞的x字串引數。first_word.split()沒有意義,因為你不能split()使用函式。你能做split()的是x。- 你在混淆
print和return。你的函式應該是return第一個單詞(不是first_word函式本身,而是你通過 split 得到的字串x),而不是print它。
這應該有效:
def first_word(x):
return x.split()[0]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441342.html
