How to convert a list of strings to lowercase
How to convert a list of strings to lowercase.
Here is a detailed step-by-step tutorial on how to convert a list of strings to lowercase:
Start by creating a list of strings that you want to convert to lowercase. Let's assume the list is called
string_listand contains the following strings: "HELLO", "WORLD", "PYTHON".Iterate through each string in the list. You can use a for loop to achieve this. Here's an example:
for i in range(len(string_list)):Inside the loop, use the
lower()method to convert each string to lowercase. Thelower()method is a built-in function in Python that returns a lowercase version of a string. Assign the lowercase string back to the same index in the list. Here's the code to do this:string_list[i] = string_list[i].lower()This code accesses the string at the current index (
i) in the list, applies thelower()method to convert it to lowercase, and assigns the lowercase version back to the same index in the list.After the loop completes, the
string_listwill contain all the strings converted to lowercase.
Here's the complete code example:
string_list = ["HELLO", "WORLD", "PYTHON"]
for i in range(len(string_list)):
string_list[i] = string_list[i].lower()
print(string_list)
Output:
['hello', 'world', 'python']
In this example, the original list string_list is modified in place to store the lowercase versions of the strings.
Alternatively, you can also use a list comprehension to achieve the same result in a more concise way:
string_list = ["HELLO", "WORLD", "PYTHON"]
string_list = [s.lower() for s in string_list]
print(string_list)
Output:
['hello', 'world', 'python']
Here, the list comprehension iterates over each string in string_list, applies the lower() method to convert it to lowercase, and creates a new list with the lowercase strings. The new list is then assigned back to string_list.
That's it! You now know how to convert a list of strings to lowercase using Python.