string title() in Python

In this article, we would cover string title() method in Python. It mainly returns with a string which has the first character of every word in Uppercase. And, rest all the characters are lowercase.The syntax of the title() method is –

string.title()

We will see how it works with appropriate examples next.

string title() in Python

Example I. Let’s say we have a string x,

x = "How are you? I am fine!"

Now, using title() method we wish to convert first character of the all the words in uppercase. We store the outcome in variable y. So, simply we can issue –

y = x.title()

To display the result, we use print() method.

print(y)

It would return with –

How Are You? I Am Fine!

Example II. Now, consider a scenario wherein the first letter is an integer.

x = "How 1st you? I 2nd FINE!"

This time, we see how it affects the outcome.

y = x.title()

To display the result –

print(y)

It would return with –

How 1St You? I 2Nd Fine!

As we can see, it converts the first character after the integer value in uppercase. So, 1st is converted to 1St and 2nd to 2Nd. Rest all work as they should i.e. converts the first character to uppercase. Also, you would notice that, we have used FINE in the string. And, when we use title() method – it converts the text to Fine. The first character F stay as it is, while following characters are converted to lowercase.

Example III. At this point, you may feel that it is pretty much everything the title() method does. But, wait there is more to it. What if, we have some repetitive pattern involving integers?

x = "Hello, 4g4g. We are waiting for 5g5g"

We store the outcome is variable y.

y = x.title()

To display the outcome using print() method –

print(y)

It would return with –

Hello, 4G4G. We Are Waiting For 5G5G

Now, notice how things are different here from what we had learnt after Example II. It converts the first character after an integer to uppercase. So, 4g4g was converted to 4G4G and 5g5g to 5G5G.

In conclusion, we have discussed how to use string title() method in Python.

Similar Posts