Online Tutorials & Training Materials | STechies.com
Register Login

How to lowercase a String in Python?

|| 0

How to lowercase a String in Python?
Stechies

In Python lower() is a build in function which converts uppercase string into lowercase string and returns it. 

In laymen language this method converts all the uppercase character present in string in lowercase character, if there is no uppercase character present in the given string it will return the original string.

Syntax:

string.lower()

Parameters: Does not take any parameters 

Returns: Returns lowercase string, if no lower case character present it return input string

Example:

# Python code to explain lower() function 
  
# Initialize a string with all uppercase characters 
str1 = 'STECHIES.COM'
print(str1.lower())

# Initialize a string with uppercase & lowercase characters 
str1 = 'StecHies.com'
print(str1.lower())

Output:

stechies.com
stechies.com

Use of lower() function in application

Example:

# Python program to compare two string using lower() function

# Initialize strings to compare
str1 = 'STECHIES'
str2 = 'SteChies'

# Compare string without using lower() function
if(str1 == str2):
    print(str1,'and ',str2,' are same')
else:
    print(str1,'and ',str2,' are not same')
    
# Compare string with lower() function
if(str1.lower() == str2.lower()):
    print(str1,'and ',str2,' are same')
else:
    print(str1,'and ',str2,' are not same')

Output:

STECHIES and  SteChies  are not same
STECHIES and  SteChies  are same

As we know that python is a case sensitive programming language so it treats capital “S” and small ‘s’ as two different characters.

So to compare string we first need to convert both the string in either small or capital letter. 

islower() function

In python islower() is a build in function, this function checks whether all the characters present in a string is lowercase or not.

Syntax:

string.islower()

Parameters: Does not take any parameters 

Returns:

True: if all characters are lowercase

False: if one or more character are uppercase

Example:

# Python program to check all characters in string is lowercase 

# Initialize strings
str1 = 'STECHIES'
str2 = 'SteChies'
str3 = 'stechies'

# Check if strings are in lowercase or not
print('String 1 STECHIES lower: ', str1.islower())
print('String 2 SteChies lower: ', str2.islower())
print('String 3 stechies lower: ', str3.islower())

Output:

String 1 STECHIES lower:  False
String 2 SteChies lower:  False
String 3 stechies lower:  True