How to Change Python String Cases

Dealing with strings in Python is common. One popular operation you may want to perform on a string is to change the case to upper or lower case.

  1. To convert a Python string to lowercase, use the built-in lower() method of a string.
  2. To convert a Python string to uppercase, use the built-in upper() method.

Here is a quick example:

"Hello, world".upper() # HELLO WORLD
"HELLO, WORLD".lower() # hello world

Let’s see other case conversions in Python.

How to Check If a String Is in Lowercase/Uppercase

You may find it useful to be able to check if a string is already in the lower or upper case. Unsurprisingly, there are built-in methods for doing this in Python.

To test if a string is in uppercase or lowercase in Python, use the built-in isupper() and islower() methods:

Here are two examples:

"Hello, world".islower() # False
"HELLO, WORLD".isupper() # True

How to Capitalize the First Letter of a String in Python

Sometimes you might only want to change the case of the first letter of a string. In this case, you don’t want to convert the entire string to upper case. Because this is such a frequent task to do, there is also a built-in method in Python for capitalizing the first letter of a word.

To capitalize the first letter of a string in Python, use the built-in capitalize() method.

Here is an example:

"hello, world".capitalize() # Hello, world

How to Swap Cases in Python

A less frequent operation to perform on a string is to convert lower case letters to upper case and vice versa. If you’re facing this situation, there is a useful built-in function you can use.

To convert each lowercase letter to uppercase and vice versa, use the swapcase() method.

For instance:

"HELLO, world".swapcase() # hello, WORLD

How to Title Case a String in Python

The title case refers to a string where the first letter of each word is capitalized.

To capitalize the first letter of each word in a string, use the title case converter by calling the title() method.

For example:

"hello, world".title() # Hello, World

Conclusion

Today you learned how to convert strings to lowercase and to uppercase in Python. Also, you saw some examples of how to apply other casings too.

Make sure you check out other useful string methods in Python.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading