I want to write a python function so that the first and last letters of the words in a string will be capitalized. The string contains lower case letters and spaces. I was thinking of doing something like:
def capitalize(s): s.title() s[len(s) - 1].upper() return s but that doesn't seem to work. Any suggestions?
For example, the string "i like cats" should become "I LikE CatS"
28 Answers
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 LikE CatS Apply title() to the whole string, then for each word in the string capitalize the last character and the append them back together.
Here's a nice one-liner. (for you golfers :P)
capEnds = lambda s: (s[:1].upper() + s[1:-1] + s[-1:].upper())[:len(s)] It demonstrates another way to get around the problems when the input is 0 or 1 characters.
It can easily be applied to a string to capitalize the individual words:
' '.join(map(capEnds, 'I like cats'.split(' '))) 'I LikE CatS' 1Try using slicing.
def upup(s): if len(s) < 2: return s.upper() return ''.join((s[0:-1].title(),s[-1].upper()))) Edit: since the OP edited in that he now needs this for every word in a string...
' '.join(upup(s) for s in 'i like cats'.split()) Out[7]: 'I LikE CatS' 4My take on a fun one-liner:
def cap_both(phrase): return ' '.join(map(lambda s: s[:-1]+s[-1].upper(), phrase.title().split())) Demo:
>>> cap_both('i like cats') 'I LikE CatS' >>> cap_both('a') 'A' Here it's what we will do:
- Break the sentence into words
- Apply a function that capitalizes first and last word of a word
- Regroup the sentences
- Write the function in (2)
So:
0)
words = "welcome to the jungle!"
1)
>>> words= words.split() 2)
>>> words = [capitalize(x) for x in words] 3)
>>> words = " ".join(words) 4)
def capitalize(word): return word[0].capitalize() + word[1:-1] + word[-1].capitalize() 1try this simple and easy to understand piece of code,
st = 'this is a test string' def Capitalize(st): for word in st.split(): newstring = '' if len(word) > 1: word = word[0].upper() + word[1:-1] + word[-1].upper() else: word = word[0].upper() newstring += word print(word) And than call the function as below,
Capitalize(st) A really old post but another fun one liner using list comprehension:
cap = lambda st: (" ").join([x.title().replace(x[-1], x[-1].upper()) for x in st.split()]) >>> cap("I like cats") 'I LikE CatS' Try this :
n=input("Enter the str: ") for i in n.split(): print(i[0].upper() +i[1:-1] +i[-1].upper(),end=' ') 1