我有一個清單。在這個串列中有各種型別的句子假設問題型別和一般句子。我想添加問號“?” 如果是疑問句,請在句末簽名。
這是我的清單
lst = ['what is Fame', 'how can you start work', 'can you learn design', 'this is text']
我試過這段代碼
for i in lst:
if 'what' or 'how' or 'can' in lst:
print(i, '?')
但沒有得到我想要的輸出。
我想實作:
what is Fame?
how can you start work?
can you learn design?
任何人都可以幫我做到這一點嗎?
感謝大家!
uj5u.com熱心網友回復:
startswith您可以通過檢查串列中是否包含特定單詞的句子來實作所需的輸出。如果是,可以在最后列印一個問號:
lst = ['what is Fame', 'how can you start work', 'can you learn design', 'this is text']
for phrase in lst:
if phrase.startswith('what') or phrase.startswith('how') or phrase.startswith('can'):
print(phrase '?')
uj5u.com熱心網友回復:
您也可以制作自己的startswith,這只是對 Python 出色的切片符號的一些簡單使用。
def startswith(s, initial):
return s[0:len(initial)] == initial
基于丹的回答:
def startswith(s, initial):
return s[0:len(initial)] == initial
lst = ['what is Fame', 'how can you start work', 'can you learn design', 'this is text']
for phrase in lst:
if startswith(phrase, 'what') or startswith(phrase, 'how') or startswith(phrase, 'can'):
print(phrase '?')
不建議用您自己的東西擴展內置String,但可以這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/448819.html
標籤:python-3.x 细绳 列表
