Skip to content Skip to sidebar Skip to footer

Python Character Rotation

Could you please help me with writing a function, which receives a character char (ie., a string of length one ), and an integer rotation. My function should return a new string of

Solution 1:

You forgot to do the checks you have mentioned and also, you need to use the chr(returnedValue) to convert the returned integer to a character. Check out the below code for the function:

def alphabet_position(letter, number):
    if len(letter) != 1:
        return -1 #Invalid input
    elif letter.isalpha() == False:
        return letter #If its not an alphabet
    else:
        ans = ord(letter) + number
        # the below if-statement makes sure the value does not overflow.
        if ans > ord('z') and letter.islower():
            ans = ans - ord('z') + ord('a')
        elif ans > ord('Z') and letter.isupper():  
            ans = ans - ord('Z') + ord('A')
        return chr(ans)

Post a Comment for "Python Character Rotation"