好的,我正在试图弄清楚如何在python中创建一个像这样的输入短语....
Self contained underwater breathing apparatus
输出这个......
SCUBA
这是每个单词的第一个字母。这与索引有关吗?也许是.upper函数?
答案 0 :(得分:21)
这是pythonic的方法:
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
答案 1 :(得分:17)
这是完成任务的最快捷方式
input = "Self contained underwater breathing apparatus"
output = ""
for i in input.upper().split():
output += i[0]
答案 2 :(得分: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
答案 3 :(得分:4)
Pythonic Idioms
<强>实施强>
input = 'Self contained underwater breathing apparatus'
output = ''.join(word[0] for word in input.split()).upper()
答案 4 :(得分:1)
另一种方式
input = 'Self contained underwater breathing apparatus'
output = ''.join(item[0].capitalize() for item in input.split())
答案 5 :(得分:1)
def myfunction(string):
return (''.join(map(str, [s[0] for s in string.upper().split()])))
myfunction("Self contained underwater breathing apparatus")
返回SCUBA
答案 6 :(得分:0)
s = "Self contained underwater breathing apparatus"
for item in s.split():
print item[0].upper()
答案 7 :(得分:0)
一些列表理解爱:
"".join([word[0].upper() for word in sentence.split()])
答案 8 :(得分: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
答案 9 :(得分:0)
我相信你也可以通过这种方式完成它。
def get_first_letters(s):
return ''.join(map(lambda x:x[0].upper(),s.split()))