How To Lowercase A String In Python

Most of the time, we have to alter the case of our string, and there isn’t a single way that works in every circumstance.

I’ll outline three methods in this blog post for converting a string to lowercase using Python.

  1. lower()
  2. casefold()
  3. swapcase()

lower() : 

It is an internal procedure that lowercases the supplied string. This method’s syntax is fairly simple: “SoMe StRiNg.” lower() will lowercase your string’s characters.

Example :

str="THIS IS SAMPLE STRING"
print("Normal string ")
print("......................................")
print(str)
print(".......................................")
print("Lowercase  string using lower() method")
print(".......................................")
print(str.lower())
print(".......................................")

casefold() :

Lower is more powerful than casefold() I’ll recommend this approach because it is more potent and returns more matches if you wish to compare two strings in Python.

The syntax for this method is “SoMe StRiNg”.casefold().

Example :

str="DEMO STRING"
print("Normal string ")
print("......................................")
print(str)
print(".......................................")
print("Lowercase  string using casefold() method")
print(".......................................")
print(str.casefold())
print(".......................................")

swapcase() :

If your string solely includes lowercase letters, swapcase() can execute a bidirectional case discussion and change the letters to uppercase.

If your string just contains uppercase letters, it will change them to lowercase, and if it contains both uppercase and lowercase letters, it will switch the cases of the letters, lowercase going first and uppercase second. Below is an illustration of these circumstances.

Example :

str="lowercase"
print("Normal string ")
print("......................................")
print(str)
print(".......................................")
print(" using swapcase() method")
print(".......................................")
print(str.swapcase())
print(".......................................")
str2="UPPERCASE"
print("Normal string ")
print("......................................")
print(str2)
print(".......................................")
print(" using swapcase() method")
print(".......................................")
print(str2.swapcase())
print(".......................................")
str3="Mix Case"
print("Normal string ")
print("......................................")
print(str3)
print(".......................................")
print(" using swapcase() method")
print(".......................................")
print(str3.swapcase())
print(".......................................")

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories