user2864748
user2864748

Reputation:

How to capitalize first and last letters of each word in a Python string?

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"

Upvotes: 5

Views: 22459

Answers (9)

Deepak
Deepak

Reputation: 490

Try this!!

def capitalize(s):
        return ' '.join(map(lambda s: s[:-1]+s[-1].upper(),
                            s.title().split()))

st = "i like cats"
print("String before:", st)
print("String after:", capitalize(st))

Upvotes: 0

Harshal Khadke
Harshal Khadke

Reputation: 1

Try this :

n=input("Enter the str: ")

for i in n.split():

    print(i[0].upper() +i[1:-1] +i[-1].upper(),end=' ')

Upvotes: -2

RajeshM
RajeshM

Reputation: 862

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'

Upvotes: 0

Amey P Naik
Amey P Naik

Reputation: 718

try 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)

Upvotes: 0

kojiro
kojiro

Reputation: 77167

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'

Upvotes: 3

jterrace
jterrace

Reputation: 67163

My 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'

Upvotes: 1

Lucas Ribeiro
Lucas Ribeiro

Reputation: 6282

Here it's what we will do:

  1. Break the sentence into words
  2. Apply a function that capitalizes first and last word of a word
  3. Regroup the sentences
  4. 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()

Upvotes: 0

roippi
roippi

Reputation: 25974

Try 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'

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239653

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.

Upvotes: 4

Related Questions