好吧,我試圖找出如何使inputed短語,如這在Python ....如何找到每個單詞的第一個字母?
自水下呼吸器
輸出這...
SCUBA
這將是每個單詞的第一個字母。這與索引有關嗎?也許是一個.upper函數?
好吧,我試圖找出如何使inputed短語,如這在Python ....如何找到每個單詞的第一個字母?
自水下呼吸器
輸出這...
SCUBA
這將是每個單詞的第一個字母。這與索引有關嗎?也許是一個.upper函數?
這裏把它做的最快方法
input = "Self contained underwater breathing apparatus"
output = ""
for i in input.upper().split():
output += i[0]
或列表的理解:'first_letters = [I [0] .upper ()for input.split()]; output =「」.join(first_letters)' – 2011-04-25 06:17:35
工作效率低下,在循環的每次迭代中構造一個新的字符串實例。 – sateesh 2011-04-25 06:50:39
非常感謝,非常感謝! – Pr0cl1v1ty 2011-04-25 12:30:31
#here is my trial, brief and potent!
str = 'Self contained underwater breathing apparatus'
reduce(lambda x,y: x+y[0].upper(),str.split(),'')
#=> SCUBA
'減少'摺疊字符串? ಠ_ಠ – 2011-04-25 06:20:02
它的工作原理!反正,我可能通過一個Haskell昆蟲:-) – nemesisfixx 2011-04-25 06:22:25
s = "Self contained underwater breathing apparatus"
for item in s.split():
print item[0].upper()
咬傷嚴重這實際上是錯誤的,因爲它會輸出 'S \ n C^\ n U \ñ 乙\ n A \ N' – 2011-04-25 06:49:35
一些列表理解愛情:
"".join([word[0].upper() for word in sentence.split()])
爲什麼不必要的字符串格式?爲什麼不只是'word [0] .upper()'? – 2011-04-25 06:20:31
哎呀,這是我嘗試了別的東西的遺物。 – manojlds 2011-04-25 06:36:19
這是做了Python的方式:
output = "".join(item[0].upper() for item in input.split())
# SCUBA
你走了。簡單易懂。
LE: 如果您有其他分隔符不是空間,您可以用文字分裂,就像這樣:
import re
input = "self-contained underwater breathing apparatus"
output = "".join(item[0].upper() for item in re.findall("\w+", input))
# SCUBA
是的,連接和生成器表達式絕對是「正確」的方式。儘管在整個輸出中調用'.upper()'會更有效,而不是每個字符。 – 2011-04-25 13:35:57
Python的成語
實現:
input = 'Self contained underwater breathing apparatus'
output = ''.join(word[0] for word in input.split()).upper()
另一種方式
input = Self contained underwater breathing apparatus
output = "".join(item[0].capitalize() for item in input.split())
另一種方式這可能是更容易的總初學者領悟:
acronym = input('Please give what names you want acronymized: ')
acro = acronym.split() #acro is now a list of each word
for word in acro:
print(word[0].upper(),end='') #prints out the acronym, end='' is for obstructing capitalized word to be stacked one below the other
print() #gives a line between answer and next command line's return
你可能有來標記的,而不是採用分體式()如果您的輸入更加複雜,即單詞「自足......」 – goh 2011-04-25 07:03:17