Lower function in python

Viewed 361

I want to make my own lower function in python

Just like we use:

>>"Hello, World!".lower()

>>hello, world!

I want to make my own lower function

I tried this code:

String = "Hello, World!"

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


print(lowerFunction(String))

But this code is too big, can we do this with a different technique?

Thanks in advance

5 Answers

There are too many challenges in your code.

  1. Doing multiple replace statement. For each of those steps, python internally creates a new string. In Python, strings are immutable.

  2. Too many if conditions.

def _lowerFunction(char):
    if 65 <= ord(char) <= 90:
        return chr(ord(char) + 32)
    return char


def lowerFunction(myStr):
    return ''.join([_lowerFunction(char) for char in myStr])

Use ord and chr to check if its is Upper Case or Lower Case charecter.

>>> ord('a') # ord example
97
>>> ord('A')
65
>>> chr(97) # chr example
'a'
>>> chr(98)
'b'

you can use ascii to replace characters.

stri = "Hello, World!"
lower_stri = ''.join([chr(ord(i)+32) if ord(i) >= 65 and ord(i) <= 90 else i for i in stri ])

This will check if the characters are among capital alphabets and replace them with small ones.

Python has special function to translate chars - str.translate()

It needs str.maketrans('ABC', 'abc') to create lookup table.

But you don't have to write ABC...Z and abc...z manually because you have it in variables string.ascii_uppercase, string.ascii_lowercase.

import string

def lower(text):
    lookup = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
    return text.translate(lookup)

text = lower("Hello, World!")

print(text)

Result

'hello, world!'

Of couse this works only for ASCII like other solutions.

For Unicode it would need all chars in maketrans()


BTW: using this you can cipher text with ROT13

import string

def rot13(text):
    lookup = str.maketrans('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
                           'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm')
    return text.translate(lookup)

text = ro13("Hello, World!")

Result

'Uryyb, Jbeyq!'

This code may help you

def lowerFunction(MyStr):
    MyStr=list(MyStr)
    for i in range(len(MyStr)):
        v=ord(MyStr[i])
        if v>=65 and v<=90:
            MyStr[i]=chr(v+32)
    MyStr=''.join(MyStr)

    return MyStr

val=lowerFunction('Hello, World!')
print(val)

One more solution using the list of lower and upper case letters. The maketrans solution is faster, so you should use that, but this solution is closer to the original one.

def lower_function(my_string):
    for lower, upper in zip(string.ascii_lowercase, string.ascii_uppercase):
        my_string = my_string.replace(upper, lower)
    return my_string

zip creates the lower-upper case pairs like that:

list(zip('abc', 'ABC')) is equal to [('a', 'A'), ('b', 'B'), ('c', 'C')]. Without list, it creates an iterator, that is fine for the for loop.

As the other solutions so far, it just works for ASCII characters, while the lower method works with others too. This will results in all lower letters:

"CSÖN CSÖN gyűrŰ Arany GYŰRŰ".lower()  # gives "csön csön gyűrű arany gyűrű"

But you can use a longer list of characters in the zip part, like

zip(string.ascii_lowercase + 'áéíóöőúüűä', string.ascii_uppercase + "ÁÉÍÓÖŐÚÜŰÄ")

But there can be some other problems, like the German scharfes s.

Related