How To Convert Uppercase To Lowercase In Python

Upper case refers to capital letters whereas lower case refers to small hand or cursive writing. The case of the text is very important as it might be used to show tone and emphasis.

But not every time we prefer emphasis and not everything is equally important in a piece of text. Hence it becomes important to be able to convert uppercase to lower case and vice versa.

This article focuses on conversion of upper case to lower case. In python, we have built in functions for the same purpose but, we would also discuss some other methods to change upper case to lower case text.

Why is there a need to convert uppercase to lowercase in python?

For various reasons we need to convert the case of a text i.e., a given string.

  1. Emphasis: as mentioned above not everything needs emphasis. It might as well happen that nothing in a complete paragraph needs to be emphasised and hence it needs to be converted in lower case.
  2. Requirement: the case of the text or string should be as per requirement. If we don’t need the text output to be in upper case we must find a way to convert it to lowercase.
  3. Readable: To differentiate a heading and regular text, the heading should be in uppercase while the regular material is generally preferred in lower case.

List of methods to change uppercase to lowercase in python

There are several ways to convert upper to lowercase in python

  1. The Built-in method (.lower())
  2. The Unicode or ASCII method
  3. The Dictionary method

Each approach in detail

1. Built-in methods

This is the most preferred method of all because of its simplicity. We use the ‘.lower()’ function to convert a string in upper case to lower case. If a text consists of both capitals and small letters, this function converts all the text to lower case.

Sample Code

a = "THAT IS MY HOUSE."
a_lower = a.lower()
print("String before using lower function: ")
print(a)
print("String after using lower function:")
print(a_lower)

Output

String before using lower function: 
THAT IS MY HOUSE.
String after using lower function:
that is my house.

Code Explanation

  1. We have a string ‘a’. It is completely in upper case.
  2. ‘a_lower’ is a variable to store the lower case converted string.
  3. To convert string a in lowercase use the .lower() function.
  4. Assign this to a_lower variable.
  5. Print a_lower

2. Unicode method

In python, we have the chr() and ord() methods to find the character from its ascii code and ascii code from the character respectively. Lets see how these methods can be used to convert upper case string to a lower case.

The capital A has an ascii code of 65 and the capital Z has an ascii code of 90. So the approach is to check if the letter’s ascii code is in between this range(65 to 90). If so , the letter would be changed, else the character remains the same.

Sample code

def upper_to_lower(s):
    n = len(s)
    s_low = ''
    for i in range(n):
        if ord(s[i]) >= 65 and ord(s[i]) <=90:
            s_low += chr(ord(s[i])+32)
        else:
            s_low += s[i]
    return s_low

s1 = 'ALPHABETS'
s2 = 'This is a simple TEXT'
print(upper_to_lower(s1))
print(upper_to_lower(s2))

Output

alphabets
this is a simple text

Code Explanation

  1. We have a function ‘upper to lower’ and it takes in a string as input
  2. The string might contain all upper case letters or some upper case and some lower case.
  3. We would traverse through the string and check if the ith character’s ascii code is in the range of 65 to 90( the ascii code of capital A and capital Z).
  4. If so then we add 32 to its ascii code and convert that into a character, this would give us the corresponding lower case character.
  5. Otherwise no changes are made and the same character is added to the string to be returned (s_low which was initially an empty string)

3. Dictionary method

In this method we make use of the dictionary data structure by python, and the fact that there are only 26 alphabets. If we save the 26 upper case alphabets as the key of the dictionary and let their value be their corresponding lowercases, we can change an uppercase letter to lowercase easily..

Sample code

def upper_to_lower(s):
	s_low = ''
	alphabet = {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd', 'E': 'e', 'F': 'f', 'G': 'g', 'H': 'h', 'I': 'i', 'J': 'j', 'K': 'k', 'L': 'l', 'M': 'm', 'N': 'n', 'O': 'o', 'P': 'p', 'Q': 'q', 'R': 'r', 'S': 's', 'T': 't', 'U': 'u', 'V': 'v', 'W': 'w', 'X': 'x', 'Y': 'y', 'Z': 'z'}
	for i in s:
    	if i in alphabet:
        	s_low += alphabet[i]
    	else:
        	s_low += i
	return s_low

s1 = 'ALPHABETS'
s2 = 'This is a simple TEXT'
print(upper_to_lower(s1))
print(upper_to_lower(s2))

Output

alphabets
this is a simple text

Code Explanation

  1. Again, we have a function upper_to_lower.
  2. We have taken a string s_low which is initially empty and would be the returned at the end of function
  3. Traversing through the given string we would check if the character is in the alphabet dictionary.
  4. If it Is there and then add its value from the dictionary to the output string.
  5. Otherwise add the string character as it is.

The best approach to convert capital letters to lowercase

As mentioned above the built in function method, .lower() is the best of all methods discussed. Some reasons for this are:

  1. Easy: this method includes no long code and is simply using a function.
  2. No mistakes: since there is no code to be written, error reduces.
  3. Faster: the built-in methods are faster than other two

Sample problems for converting uppercase to lowercase

Sample Problem 1:

In CSS, all property names and most keyword values are primarily formatted in the kebab case. It is inconvenient to put hyphens in place of space to make a function to convert the input property to a kebab format. The input string contains spaces in place of hyphens.

def kebabcase(st):
    kebab = ''
    st = st.lower()
    for i in st:
        if i == ' ':
            kebab += '-'
        else:
            kebab += i
    return kebab
p1 = 'Only Of Type'
p2 = 'Only Child'
p3 = 'Last Of Child'
p4 = 'Last Child'
p5 = 'Nth Last Of Type'
print(kebabcase(p1))
print(kebabcase(p2))
print(kebabcase(p3))
print(kebabcase(p4))
print(kebabcase(p5))

output

only-of-type
only-child
last-of-child
last-child
nth-last-of-type

Explanation

  1. Since the question asks for a function, the def keyword is used to create the function ‘kebabcase’
  2. Use the ‘.lower()’ method to completely convert the given string in lower case.
  3. The variable ‘kebab’ is initially empty and will store the output kebabcase string.
  4. Traverse the given string and if a space is encountered, add a hyphen in place.
  5. Otherwise add the string.

Sample Problem 2:

While typing in a text editor, sometimes we miss to capitalize the first letter of the sentence or it might happen that the shift button is pressed later. This makes the first letter small but the next one capital. Write a function that keeps a check on the case and doesn’t let you make these mistakes. A program that capitalizes the first letter of a statement, and keeps the rest in lower case.

def upper_to_lower(s):
    s_low = ''
    n = len(s)
    if ord(s[0]) >= 97 and ord(s[0]) <=122:
        s_low += chr(ord(s[0]) -32)
    for i in range(1,n):
        if i>2 and s[i-2] =='.':
            if ord(s[i]) >=97 and ord(s[i])<=122:
                s_low += chr(ord(s[i]) - 32)  
            else:
                s_low += s[i]
        elif ord(s[i]) >= 65 and ord(s[i]) <=90:
            s_low += chr(ord(s[i]) +32)
        else:
            s_low += s[i]
        
    return s_low
inp = 'gOOd Morning. this is TO Inform all students That the school is organizing an annual function. iNTERested students may give their Names to theIr respective class Teachers.'
ans = upper_to_lower(inp)
print(ans)

Output

Good morning. This is to inform all students that the school is organizing an annual function. Interested students may give their names to their respective class teachers.

Explanation

  1. We declare a function named ‘upper_to_lower’ which takes a string as an argument.
  2. The given argument is the one that needs correction.
  3. The variable ‘s_low’ is initially an empty string, since it would be used to store the answer.
  4. Check if the first character of the text is capital or not(if the letter is in lower case i.e. if its ascii code lies in range 97 to 122 both included).  If not capital, change it by subtracting 32 from its ascii code and then converting it into the corresponding character using the chr() function.
  5. Now, run a loop till the length of the string given starting from index 1.
  6. Check if there is a full stop before the letter. If so and the character is not in upper case, capitalize it.
  7. If it is already in uppercase, add it to the string.
  8. Next, check if the character ‘i’ has an ASCII code in range 65 to 90, both inclusive.
  9. If so, then add 32 to its ASCII code and convert into character, as it is an uppercase character.
  10. Add this character to the string s_low. This character would be the corresponding lowercase.
  11. But if the character is not in uppercase, add it directly to the string s_low.
  12. Finally return s_low.

Sample Problem 3:

The domain name in an email address is case insensitive and hence, any case can be entered while typed by the user. Create an autocorrect case or ignore case function, which takes the domain name and converts it to lowercase.

email1 = '[email protected]'
email2 = '[email protected]'


def convert(email):
    alphabets =  {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd', 'E': 'e', 'F': 'f', 'G': 'g', 'H': 'h', 'I': 'i', 'J': 'j', 'K': 'k', 'L': 'l', 'M': 'm', 'N': 'n', 'O': 'o', 'P': 'p', 'Q': 'q', 'R': 'r', 'S': 's', 'T': 't', 'U': 'u', 'V': 'v', 'W': 'w', 'X': 'x', 'Y': 'y', 'Z': 'z'}
    slice1 = email.index('@')
    slice2 = email.index('.')
    domain = ''
    for i in range(slice1+1, slice2):
        if email[i] in alphabets:
            domain += alphabets[email[i]]
        else:
            domain += email[i]
    ans = email[:slice1+1] + domain + email[slice2:]
    return ans
print(convert(email1))
print(convert(email2))

Output

[email protected]
[email protected]

Explanation

  1. We have a function convert, that takes in the email Id.
  2. Declare a dictionary alphabet with capital letters as the key and their corresponding lower case letters as value.
  3. Since we just need the domain name which begins after ‘@’ and ends before ‘.’, we slice the string (email) accordingly.
  4. Now, just traverse the domain name if the letter of the domain name is in alphabets i.e. it is an uppercase letter and needs to be converted.
  5. Hence, add the value of that key from the alphabet dictionary.
  6. Otherwise, add the character simply.
  7. Store the final email in a variable, using string concatenation.

Conclusion

In conclusion, there are three ways to convert an upper case string to lower case, the built in method, .lower; the Unicode or ascii method; and the list method. Using the lower method by python is the best as it is hassle free. And needs no array or list to be declared.

The examples given later in the article help to understand the use of converting capitals to lower cases.