2011-04-25 173 views
12

好吧,我試圖找出如何使inputed短語,如這在Python ....如何找到每個單詞的第一個字母?

自水下呼吸器

輸出這...

SCUBA

這將是每個單詞的第一個字母。這與索引有關嗎?也許是一個.upper函數?

+1

你可能有來標記的,而不是採用分體式()如果您的輸入更加複雜,即單詞「自足......」 – goh 2011-04-25 07:03:17

回答

16

這裏把它做的最快方法

input = "Self contained underwater breathing apparatus" 
output = "" 
for i in input.upper().split(): 
    output += i[0] 
+4

或列表的理解:'first_letters = [I [0] .upper ()for input.split()]; output =「」.join(first_letters)' – 2011-04-25 06:17:35

+0

工作效率低下,在循環的每次迭代中構造一個新的字符串實例。 – sateesh 2011-04-25 06:50:39

+0

非常感謝,非常感謝! – Pr0cl1v1ty 2011-04-25 12:30:31

5
#here is my trial, brief and potent! 
str = 'Self contained underwater breathing apparatus' 
reduce(lambda x,y: x+y[0].upper(),str.split(),'') 
#=> SCUBA 
+0

'減少'摺疊字符串? ಠ_ಠ – 2011-04-25 06:20:02

+2

它的工作原理!反正,我可能通過一個Haskell昆蟲:-) – nemesisfixx 2011-04-25 06:22:25

0
s = "Self contained underwater breathing apparatus" 
for item in s.split(): 
    print item[0].upper() 
+3

咬傷嚴重這實際上是錯誤的,因爲它會輸出 'S \ n C^\ n U \ñ 乙\ n A \ N' – 2011-04-25 06:49:35

0

一些列表理解愛情:

"".join([word[0].upper() for word in sentence.split()]) 
+1

爲什麼不必要的字符串格式?爲什麼不只是'word [0] .upper()'? – 2011-04-25 06:20:31

+0

哎呀,這是我嘗試了別的東西的遺物。 – manojlds 2011-04-25 06:36:19

18

這是做了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 
+2

是的,連接和生成器表達式絕對是「正確」的方式。儘管在整個輸出中調用'.upper()'會更有效,而不是每個字符。 – 2011-04-25 13:35:57

3

Python的成語

  • 使用過海峽發電機表達。 split()
  • 通過將upper()移到循環外部的一個調用來優化內部循環。

實現:

input = 'Self contained underwater breathing apparatus' 
output = ''.join(word[0] for word in input.split()).upper() 
0

另一種方式

input = Self contained underwater breathing apparatus

output = "".join(item[0].capitalize() for item in input.split())

0

另一種方式這可能是更容易的總初學者領悟:

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 
相關問題