Rotate a word in Python with a key

Viewed 4446

Write a function called rotate_word() that takes a string and an integer as parameters, and returns a new string that contains the letters from the original string rotated by the given amount. Rotate_word('cheer',7) == 'jolly', Rotate_word('melon', -10) = 'cubed',**

My Python code is:

def Rotate_word(str_, num_):
    result = ''
    for i in str_:
        i = chr(ord(i) + num_)
        result = result + i
    return (result)

str_ =input("Enter a string: ")
num_ = int(input("Enter rotate number: "))
print (Rotate_word(str_,num_))

It gives output like:

Enter a string: cheer  
Enter rotate number: 7  
jolly   

Which is correct.

Enter a string: melon  
Enter rotate number: -10  
c[bed  

This is wrong the correct answer is cubed

What am I doing wrong and how can I fix it?

4 Answers

Assuming you only need lowercase characters, you need to wrap it around if it "overflows", which means if it goes beyond z or before a:

left_bound = ord("a")
right_bound = ord("z")

and then do something like this:

char_num = ord(i) + num_
while char_num > right_bound: char_num -= 26
while char_num < left_bound: char_num += 26
i = chr(char_num)
result = result + i

There are shorter and more elegant solutions, but this is the most straight forward fix

The problem is that you need to "wrap around" when going below 'a' or above 'z'.

However instead of using chr and ord you can simply using str.translate with str.maketrans:

import string

def Rotate_word(str_, num_):
    # Create a translation table from lowercase characters to shifted lowercase chars
    tab = str.maketrans(string.ascii_lowercase, 
                        string.ascii_lowercase[num_:] + string.ascii_lowercase[:num_])
    return str_.translate(tab)

str_ =input("Enter a string: ")
num_ = int(input("Enter rotate number: "))
print(Rotate_word(str_,num_))

It would need a bit of additional work to make it also handle uppercase letters. But it produces the correct output for 'melon' and -10 and 'cheer' and 7.

s=input()
n=int(input())
s2=""
for l in s:
    s2=s2+chr(ord(l)+n)
print(s2)    
str_ ='melon'
num_ = -10
cstr=''
for i in str_:
  t= (ord(i) + num_)
  if t<97:
    t=123-(97-t)
  cstr =cstr + chr(t)
print(cstr)

output is cubed
Related