python - Capitalized Word Function -
i writing function should take string input , return string every first letter of every word capital letter, have achieved degree.
my code:
string = input("please enter string:") def capitalize_words(string): split = string.split() letter1 = '' letter2 = '' letter3 = '' str1 = split[0] str2 = split[1] str3 = split[2] in str1: if in str1[0]: first = i.upper() else: letter1 = letter1 + string1 = (first+letter1) in str2: if in str2[0]: first = i.upper() else: letter2 = letter2 + string2 = (first+letter2) in str3: if in str3[0]: first = i.upper() else: letter3 = letter3 + string3 = (first+letter3) result = string1+' '+string2+' '+string3 return result func = capitalize_words(string) print(func)
input:
please enter string:herp derp sherp
output:
herp derp sherp
however inflexible because can enter 3 words spaces no more no less , makes rather primal program. able enter , desired result of first letter of every word being capital letter no matter how many words enter.
i fear skills far able get, can please improve program if possible.
use str.title()
achieve want in 1 go.
but process words in sentence, use loop instead of series of local variables; here version same doing arbitrary number of words:
for i, word in enumerate(split): split[i] = word[0].upper() + word[1:] result = ' '.join(split)
i used string slicing select first character, , first character of word. note use of enumerate()
give counter wich can replace words in split
list directly.
Comments
Post a Comment