Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert case of elements in a list of strings in Python
As part of data manipulation, we often need to standardize the case of strings in a list. In this article, we will see how to convert a list of string elements with mixed cases to a uniform case using Python's built-in string methods.
Using lower() with map()
The lower() function converts all characters in a string to lowercase. We can use map() with lambda to apply this function to each element in the list.
Example
days = ['MoN', 'TuE', 'FRI']
# Given list
print("Given list:")
print(days)
# Convert to lowercase using map() and lambda
result = list(map(lambda x: x.lower(), days))
# Print output
print("New all lowercase list:")
print(result)
Given list: ['MoN', 'TuE', 'FRI'] New all lowercase list: ['mon', 'tue', 'fri']
Using upper() with List Comprehension
The upper() function converts all characters in a string to uppercase. We can use list comprehension to apply this function to each element efficiently.
Example
days = ['MoN', 'TuE', 'FRI']
# Given list
print("Given list:")
print(days)
# Convert to uppercase using list comprehension
result = [x.upper() for x in days]
# Print output
print("New all uppercase list:")
print(result)
Given list: ['MoN', 'TuE', 'FRI'] New all uppercase list: ['MON', 'TUE', 'FRI']
Using title() for Title Case
The title() function converts the first character of each word to uppercase and the rest to lowercase.
Example
names = ['john doe', 'JANE SMITH', 'bob JONES']
# Given list
print("Given list:")
print(names)
# Convert to title case
result = [x.title() for x in names]
# Print output
print("New title case list:")
print(result)
Given list: ['john doe', 'JANE SMITH', 'bob JONES'] New title case list: ['John Doe', 'Jane Smith', 'Bob Jones']
Comparison of Methods
| Method | Function | Best For |
|---|---|---|
| List Comprehension | Most readable | Simple transformations |
| map() with lambda | Functional approach | Complex transformations |
| For loop | Most explicit | Additional processing needed |
Conclusion
Use lower(), upper(), or title() with list comprehension for clean, readable code. The map() function with lambda is useful for more functional programming approaches to case conversion.
