How to Convert String to Lowercase in Python 2 and 3

Convert string to lowercase in Python 3

str type since Python 3.0 contains by default Unicode characters, meaning any string like "unicode example", 'unicode example 2' is stored as Unicode.

Therefore, you could use str.lower() to convert any string to lowercase in Python 3.

exampleString = "CaseString"
exampleString.lower()
#Out: 'casestring'

exampleString = "СтрокаСлучая"
exampleString.lower()
#Out: 'строкаслучая'

Convert string to lowercase in Python 2.7

str type in Python 2.7 is not stored as Unicode, and Unicode strings are instances of the unicode type. We must distinguish whether the string is an ASCII string or unicode string when we convert the string to lowercase.

ASCII type

It is the same with the method used in Python 3. str.lower() converts the str to lowercase.

exampleString = "CaseStringExample"
exampleString.lower()
#Out: 'casestringexample'

unicode type

If the characters in the string is unicode type and it is not explicitly represented in unicode type, str.lower() method doesn’t convert the string to lower case at all.

exampleString = "СтрокаСлучая"
print exampleString.lower()
#Out: СтрокаСлучая

exampleString.lower() == exampleString
#Out: True

Python objects to non-ASCII bytes in a string with no-encoding given because the intended coding is implicit.

Using Unicode literals but not str

exampleUnicodeString = u"СтрокаСлучая"
exampleUnicode
#u'\u0421\u0442\u0440\u043e\u043a\u0430\u0421\u043b\u0443\u0447\u0430\u044f'
exampleUnicodeString.lower()
#u'\u0441\u0442\u0440\u043e\u043a\u0430\u0441\u043b\u0443\u0447\u0430\u044f'

print exampleUnicodeString.lower()
#Out: строкаслучая

You could see here that the first character of the string is converted from \u0421 to \u0441.

Convert a str to unicode

If the given string is in the form of str, we need to first convert it to unicode before lower-case conversion.

exampleString = "СтрокаСлучая"
print exampleString.decode('utf-8').lower()
#Out: строкаслучая