In this tutorial, we will learn about python lowercase. We will understand how to perform the lowercase operation in python. so let’s get started.
Introduction to python lowercase
Python has an inbuild function called lower() which is used to perform the lowercase operation in python. The lower () function will convert all the uppercase letters to the lowercase
Syntax of python lowercase
The lower() function in python follows the below syntax
string.lower()
The lower() function does not takes any parameter and returns the lowercase string from the given string.
Python convert a string to lowercase
Let’s take a string and try to convert it into lowercase using the lower() function.
a = "STRING TO BE LOWERED" b = a.lower() print(b)
The above code prints the string in lowercase
The .lower() function converts all occurrences of uppercase to lower as shown below
a = "STRinG To bE LoWEr" b = a.lower() print(b)
Python lowercase list
The .lower() function can also be used to convert the element present in the list into lowercase. Let’s take the below example.
l = ["JOHN","JACK","HARRY"] l_lower = [x.lower() for x in l] print(l_lower)
we use the lower function to loop through the entire list and convert the characters to lowercase.
Convert textfile to lowercase
So far we have seen how to convert a string or list into lowercase. In this session, we will understand how to convert the case of all characters in a textfile.
Below is the content of a textile name test_file.txt
Let’s use the below code to convert all characters to lowercase.
## Read the content of file with open('./test_file.txt', 'r') as input_file: # open another file to write to in append mode with open('./test_file_lower.txt', 'a') as output_file: # read each line from input file for line in input_file: # change case for the line and write # it into output file output_file.write(line.lower())
We use the open function to open two files, one to read from and the other to write to. While writing each line to the output file we are applying the lower() function.
Check the content of the output file to verify the data.
Conclusion
I hope you have liked this small tutorial about python lowercase. Please do let me know if you need any more input.