好的,我正在尝试弄清楚如何在Python中制作像这样输入的短语....
Self contained underwater breathing apparatus
输出这个...
SCUBA
每个单词的第一个字母会是什么?这与索引相关吗?也许可以使用 .upper 函数?
好的,我正在尝试弄清楚如何在Python中制作像这样输入的短语....
Self contained underwater breathing apparatus
输出这个...
SCUBA
每个单词的第一个字母会是什么?这与索引相关吗?也许可以使用 .upper 函数?
这是使用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
.upper()
应用于整个输出,而不是每个字符,会稍微更有效率一些。 - Ben Hoyt以下是最快的实现方法
input = "Self contained underwater breathing apparatus"
output = ""
for i in input.upper().split():
output += i[0]
first_letters = [i[0].upper() for i in input.split()]
; 输出结果为:output = "".join(first_letters)
。 - David Wolever#here is my trial, brief and potent!
str = 'Self contained underwater breathing apparatus'
reduce(lambda x,y: x+y[0].upper(),str.split(),'')
#=> SCUBA
reduce
折叠字符串?ಠ_ಠ - David WoleverPythonic习惯用法
实现:
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())
def myfunction(string):
return (''.join(map(str, [s[0] for s in string.upper().split()])))
myfunction("Self contained underwater breathing apparatus")
SCUBA
我相信你也可以用这种方式完成它。
def get_first_letters(s):
return ''.join(map(lambda x:x[0].upper(),s.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
s = "Self contained underwater breathing apparatus"
for item in s.split():
print item[0].upper()
S\n C\n U\n B\n A\n
。 - Gabi Purcaru "".join([word[0].upper() for word in sentence.split()])
word[0].upper()
? - David Wolever