lettura simple

Python's capitalize() Method

Hey there! Let me introduce you to Python's handy capitalize() method. It's a simple way to change the first character of a string to uppercase. Here's how it works:

string.capitalize()

The term "string" refers to the variable you'd like to apply the capitalize() method to.

You can use this method with any String type objects.

Now, let's walk through a real-life example together.

First, create a string variable.

>>> text = "hello world

Next, apply the capitalize() method to the string.

>>> text.capitalize()

Voilà! The first letter of the string is now uppercase.

Hello world

Keep in mind that the capitalize() method doesn't change the original string. Instead, it returns a new capitalized string.

So, if you want to save your updated string, just assign it to a new variable.

>>> new_variable = text.capitalize()

Or, you can assign it back to the original variable:

>>> text = text.capitalize()

One more thing: capitalize() only changes the first character of the string to uppercase.

The rest of the characters stay the same.

P.S. If you'd like to capitalize the first letters of all the words in a string, give the title() method a try. And if you want to make every letter uppercase, check out the upper() method. Happy coding!




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin