Change case of Python string and list to lower
You can easily lowercase a Python string by using the lower() function. Lists can be converted to lowercase using a list comprehension:
#for strings my_str.lower() # and for lists low_lst = [e.lower() for e in cap_lst]
Convert a string to lower case
Consider the following capitalized Python string that we will be working with along this tutorial
Changing the string case is easily accomplished with the string lower() function:
low_str = cap_str.lower() print (low_str)
This will render the following string:
We can use the islower() function to ensure that all letters in the string are lower cased.
This will return True, as we have previously changed the case of the entire string to lower.
Note: use the capitalize() function to change to lower case all letters in a word except the first one.
Lowercase a list with Python
Now let’s assume that we have a Python list which we want to convert to small letter case. We use the split() string function in order to turn a string to a Python array.
cap_lst = cap_str.split(',')
Let’s look into our list:
print( cap_lst )
This will render the following result:
If we try to apply the lower() function on a list, we’ll get an AttributeError exception. The reason is that we are trying to use the dot notation to call a function / method that exists for strings but not for lists.
AttributeError: 'list' object has no attribute 'lower'
We can work this around using a simple list comprehension.
low_lst = [e.lower() for e in cap_lst] print(low_lst)
Here’s our lower cased list:
Change case pandas column or series
Last topic for this tutorial is to lower case a Pandas DataFrame column / Series. Assume the following Pandas Series:
import pandas as pd cap_s = pd.Series(cap_lst)
We can easily convert the Series to lower case by using the dt accessor. Using dt allows to apply string functions such as capitalize, upper, lower and so forth to Pandas columns.
low_s = cap_s.str.lower() print (low_s)
THis renders the following Pandas Series: