每个单词的第一个字母大写,以短语为单位。

17

好的,我正在尝试弄清楚如何在Python中制作像这样输入的短语....

Self contained underwater breathing apparatus

输出这个...

SCUBA

每个单词的第一个字母会是什么?这与索引相关吗?也许可以使用 .upper 函数?


1
如果您的输入更加复杂,例如“自包含...”,则可能需要对单词进行标记化而不是使用split()。 - goh
11个回答

25

这是使用Pythonic的方式:

output = "".join(item[0].upper() for item in input.split())
# SCUBA

这就是答案,简短易懂。

附加说明: 如果分隔符不是空格,你可以按单词进行分割,像这样:

import re
input = "self-contained underwater breathing apparatus"
output = "".join(item[0].upper() for item in re.findall("\w+", input))
# SCUBA

2
是的,使用join和生成器表达式绝对是“正确”的方法。不过,将.upper()应用于整个输出,而不是每个字符,会稍微更有效率一些。 - Ben Hoyt

17

以下是最快的实现方法

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

4
或者使用列表推导式:first_letters = [i[0].upper() for i in input.split()]; 输出结果为:output = "".join(first_letters) - David Wolever
2
可以运行但效率低下,在每次循环迭代中构造一个新的字符串实例。 - sateesh
你需要导入任何东西来使用 .upper 吗?因为我稍微编辑了你的代码,似乎出现了基于 .upper 的错误。另外,.split 到底是做什么用的? - Pr0cl1v1ty
1
.split() 返回由空格分隔的字符串列表。你遇到了什么错误? - Penang

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

1
使用reduce折叠字符串?ಠ_ಠ - David Wolever
2
它运行了!不过,可能我被 Haskell 虫子咬得很惨。 :-) - JWL

4

Pythonic习惯用法

  • 使用生成器表达式代替str.split()
  • 通过将upper()移动到循环外部的一个调用来优化内部循环。

实现:

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

1
另一种方式。
input = 'Self contained underwater breathing apparatus'

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

1
def myfunction(string):
    return (''.join(map(str, [s[0] for s in string.upper().split()])))

myfunction("Self contained underwater breathing apparatus")

返回 SCUBA

0

我相信你也可以用这种方式完成它。

def get_first_letters(s):
    return ''.join(map(lambda x:x[0].upper(),s.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

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

4
实际上这是错误的,因为它会输出 S\n C\n U\n B\n A\n - Gabi Purcaru

0
一些列表推导爱:
 "".join([word[0].upper() for word in sentence.split()])

1
为什么要使用不必要的字符串格式?为什么不直接使用 word[0].upper() - David Wolever
哎呀,那是我之前尝试的某个东西的遗留物。 - manojlds

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接