2011-04-25 177 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 
相关问题