How to Lowercase a String in Python In Python, strings are immutable, meaning that once you create a string, you cannot change it. However, you can create a new string that is a modified version of an existing string. One common modification is to convert all the characters in a string to lowercase. In this article, we'll discuss how to lowercase a string in Python using several methods.
Method 1: Using the lower() Method
The most straightforward way to lowercase a string in Python is to use the lower() method. This method returns a new string with all the characters in the original string converted to lowercase.
Here's an example:
s = "HELLO WORLD" lowercase_s = s.lower() print(lowercase_s) # Output: "hello world"
The lower() method is available for all strings in Python and does not require any additional imports.
Method 2: Using the str.lower() Function
Another way to lowercase a string in Python is to use the str.lower() function. This function takes a string as an argument and returns a new string with all the characters in the original string converted to lowercase.
Here's an example:
s = "HELLO WORLD" lowercase_s = str.lower(s) print(lowercase_s) # Output: "hello world"
The str.lower() function is available in all versions of Python and does not require any additional imports.
Method 3: Using the unicode.lower() Method (Python 2 Only)
If you are using Python 2, you can lowercase a string using the unicode.lower() method. This method returns a new string with all the characters in the original string converted to lowercase.
Here's an example:
s = "HELLO WORLD" lowercase_s = s.lower() print(lowercase_s) # Output: "hello world"
Note that the unicode.lower() method is only available in Python 2 and is not compatible with Python 3.