DEV Community

Cover image for How do I convert a string to lowercase in Python?
Isabelle M.
Isabelle M.

Posted on • Originally published at 30secondsofcode.org

How do I convert a string to lowercase in Python?

str.lower()

Python's standard method for converting a string to lowercase is str.lower() and is compatible with both Python 2 and Python 3. While this is the standard way for most cases, there are certain cases where this method might not be the most appropriate, especially if you are working with Unicode strings.

'Hello'.lower()               # 'hello'
'Straße'.lower()              # 'straße'
'Straße'.upper().lower()      # 'strasse'
# Example of incorrect result when used for unicode case-insensitive matching
'Straße'.upper().lower() == 'Straße'.lower() # False ('strasse' != 'straße')
Enter fullscreen mode Exit fullscreen mode

str.casefold()

Python 3 introduced str.casefold(), which is very similar to str.lower(), but more aggressive as it is intended to remove all case distinctions in Unicode strings. It implements the casefolding algorithm as described in section 3.13 of the Unicode Standard.

'Hello'.casefold()            # 'hello'
'Straße'.casefold()           # 'strasse'
'Straße'.upper().casefold()   # 'strasse'
# Returns the correct result when used for unicode case-insensitive matching
'Straße'.upper().casefold() == 'Straße'.casefold() # True
Enter fullscreen mode Exit fullscreen mode

Do you like short, high-quality code snippets and articles? So do we! Visit 30 seconds of code for more articles like this one or follow us on Twitter for daily JavaScript, React and Python snippets! 👨‍💻

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay