How to convert string to lowercase in Python?
#Is there any way to convert an entire user inputted string from uppercase, or even part uppercase to lowercase?
Answer: The Python string lower() inbuild function converts all characters in a string into lowercase characters and returns it.
Syntax
The syntax of lower() method below:
string.lower()
Parameters
Python lower() function doesn’t take any parameters.
Return value
The Python lower() function returns the lowercased string of the given string. If there are upper case characters in the string then it will also convert into lowercase characters.
Python lowercase function Examples
Let’s learn how to use lower() function in deferent places.
Example 1: Convert Python string to lowercase
An example of creating and initiated the string variable. Where “str1” has uppercase characters, which will convert in lowercase.
The second variable”str2″ has a combination of string and numeric value. It will also convert all characters in lowercase without an error.
If given strings have no uppercase characters, then it will return the original string.
# example string str1 = "I WANT IT SHOULD BE LOWERCASE!" print(string.lower()) # string with numbers # all alphabets whould be lowercase str2 = "L8w9rCas99!" print(string.lower())
Output:
i want it should be lowercase!
l8w9rcas99!
Example 2: Why/Where lower() function is used in a program?
Answer: As you know lower() function is use to converting uppercase characters in lowercase, but where it will useful?
It will use when you are trying to compare string. See the below example without using a string in if conditions.
firstString = "PYTHON!" secondString = "PyThOn!" if(firstString == secondString): print("The strings are same.") else: print("The strings are not same.")
Output: The strings are not same.
So as you can see program output will shoe strings are not the same because some characters are in uppercase in the first string.
Let’s try solve this problem by using a lower() function:-
firstString = "PYTHON!" secondString = "PyThOn!" if(firstString.lower() == secondString.lower()): print("The strings are same.") else: print("The strings are not same.")
Output: The strings are same.
Example 3: How to convert Python lowercase first letter?
Answer: For converting a specific character in the string to lowercase you have to use an index value of string and lower() function. Additional use arithmetic operator to contact remain string.
See below example converting first letter into a lowercase letter.
str = "PYTHON!" print(str[0].lower() + str[1:])
Do comment if you have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7