Convert a string to uppercase and lowercase in Python
This post will discuss how to convert a string to uppercase and lowercase in Python.
1. Convert to uppercase
The built-in function str.upper provides a simple, clean way to convert a string to uppercase in Python. Here’s an example:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'abc' s = s.upper() print(s) # ABC |
If you just need to check whether all the characters in the string are uppercase, you can use the str.isupper function.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = 'ABC' if s.isupper(): print("String is uppercase") else: print("String is not uppercase") |
2. Convert to lowercase
Similarly, you can use the built-in str.lower function for converting the string to lowercase:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': s = 'ABC' s = s.lower() print(s) # abc |
If you just need to check whether all the characters in the string are lowercase, you can use the str.islower function.
|
1 2 3 4 5 6 7 8 9 |
if __name__ == '__main__': s = 'abc' if s.islower(): print("String is lowercase") else: print("String is not lowercase") |
That’s all about converting a string to uppercase and lowercase in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)