Function That Receives and Rotates a Text

165 views Asked by At

Could you please help me with writing a function, which receives a character char (ie., a string of infinite length), and an integer rotation. My function should return a new string of infinite length, the resulting of rotating char by rotation number of places to the right. My output for this code should be like this:

Type a message:
Hey, you!
Rotate by:
5
Mjd, dtz!

So far this is what I have:

def rotate_character(char, rot):
   move = 97 if char.islower() else 65
   return chr((ord(char) + rot - move) % 26 + move)

char = input('Type a message: ')
rot = int(input('Rotate by: '))
print(rotate_character(char, rot))

and this is the error message I get:

TypeError: ord() expected a character, but string of length 9 found on line 3
2

There are 2 answers

0
Joran Beasley On
def rotated_ascii(rotate_by):
    return ascii_uppercase[rotate_by:] + ascii_uppercase[:rotate_by] + ascii_lowercase[rotate_by:] + ascii_lowercase[:rotate_by]


def rotate_text(t,rotate_by):
    tab = str.maketrans(ascii_uppercase + ascii_lowercase,rotated_ascii(rotate_by))
    return t.translate(tab)

print(rotate_text("Hey, You!",5))
0
Augusto Yao On
def rotate_character(char, rot):
    res = ""
    for c in char:
        if c.isalpha():
            move = 97 if c.islower() else 65
            res += chr((ord(c) + rot - move) % 26 + move)
        else:
            res += c
    return res

ord return the Unicode code point for a one-character string. Looking at your code, the first parameter passing to rotate_character is a string whose length might be larger than 1.