Skip to content

709. To Lower Case | LeetCode | Solution | Python

Here is the link to the problem. An easy problem to solve.

The problem description is easy. Given a string and we have to returns it in lowercase. We can solve this problem in many ways.

The first one is we will check each character. If it is uppercase we will change it to lowercase. If it’s not, we will keep it the same as it is. We will use the lower() function to do this.

class Solution:
    def toLowerCase(self, str: str) -> str:
        
        result = ''
        
        for let in str:
            if let.isupper():
                result += let.lower()
            else:
                result += let
        
        return result

We can do the previous one in a much shorter way.

class Solution:
    def toLowerCase(self, str: str) -> str:
        
        return str.lower()

We can also solve this problem using the ASCII method. There we will just change the ASCII value if the character is uppercase. If the string is A, we will use the ASCII value of a. To do this, we will add 32 with the current ASCII value. Click here to know more about ASCII.

See the following code.

class Solution:
    def toLowerCase(self, str: str) -> str:
        
        result = ''
        
        for let in str:
            if let.isupper():
                result += chr(ord(let) + 32)
            else:
                result += let
        
        return result

The ord() function returns the ASCII value of a character. And the chr() function returns the character from an ASCII value.

If you submit the code in LeetCode, it will be accepted.

Published inLeetCode

Comments are closed.