Upper case first letter of each word in a phrase

前端 未结 10 1539
栀梦
栀梦 2020-12-03 21:08

Ok, I\'m trying to figure out how to make a inputed phrase such as this in python ....

Self contained underwater breathing apparatus

output

相关标签:
10条回答
  • 2020-12-03 21:46

    Here's the quickest way to get it done

    input = "Self contained underwater breathing apparatus"
    output = ""
    for i in input.upper().split():
        output += i[0]
    
    0 讨论(0)
  • 2020-12-03 21:46

    This is the pythonic way to do it:

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

    There you go. Short and easy to understand.

    LE: If you have other delimiters than space, you can split by words, like this:

    import re
    input = "self-contained underwater breathing apparatus"
    output = "".join(item[0].upper() for item in re.findall("\w+", input))
    # SCUBA
    
    0 讨论(0)
  • 2020-12-03 21:46

    Another way which may be more easy for total beginners to apprehend:

    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 讨论(0)
  • 2020-12-03 21:49

    Another way

    input = 'Self contained underwater breathing apparatus'
    
    output = ''.join(item[0].capitalize() for item in input.split())
    
    0 讨论(0)
  • 2020-12-03 21:53

    Some list comprehension love:

     "".join([word[0].upper() for word in sentence.split()])
    
    0 讨论(0)
  • 2020-12-03 21:59
    #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 讨论(0)
提交回复
热议问题