Write a Python program to capitalize first and last letters of each word of a given
Answers
Answer:
def capitalize(s):
s, result = s.title(), ""
for word in s.split():
result += word[:-1] + word[-1].upper() + " "
return result[:-1] #To remove the last trailing space.
print capitalize("i like cats")
Output
I recently solved this question on hackerrank, it is tricky but if you think, it is simple.
s = input()
def duplicates(lst, item):
return [i for i, x in enumerate(lst) if x == item]
s = list(s)
space_indexes = duplicates(s,' ')
s[0] = s[0].upper()
for x in space_indexes:
index = int(x)
s[index+1] = s[index+1].upper()
s = ''.join(s)
print( s)
I basically checked for the indexes of the spaces in splitted list and then capitalized all the characters right after the space.
But, I used s[0] = s[0].upper() because the first word should always be capital.
Hope it helps! :)
for word in st.split():
print(word[0].upper()+word[1:-1]+word[-1].upper(), sep=' ', end=' ')
---Simple isn't it?
for word in st.split():
if word > 1: print(word[0].upper()+word[1:-1]+word[-1].upper(), sep=' ', end=' ')
Sentence = input()
For x in sentence.split():
Sentence = sentence.replace(x,x.capitalize())
Print(sentence)