def rotate_word(word,number):
new_word_number=[]
new_word=[]
for letter in word:
new_word_number.append(ord(letter)+number)
new_word.append(chr(new_word_number))
return new_word
rotate_word('xyz',2)
This code is showing error TypeError: an integer is required (got type list)
No idea what you're trying to achieve, but here's a code that will work:
def rotate_word(word, number):
new_word = []
for letter in word:
new_word.append(chr(ord(letter) + number))
return ''.join(new_word)
print(rotate_word('xyz', 2))
Will print z{|
Note that you don't need two intermediary lists. Also, using ''.join(your_list)
will allow to consolidate the resulting list into a string so your function returns the same type it's given.
Btw, if your initial goal was to achieve character rotation like rot13 (in your case rot2), you could use a smarter function that also only deals with alphabet characters to make the output portable (only printable characters):
def rotX(string: str, shift: int = 13):
"""
RotX for only A-Z and a-z characters
"""
try:
return ''.join(
[chr(ord(n) + (shift if 'Z' < n < 'n' or n < 'N' else -shift)) if ('a' <= n <= 'z' or 'A' <= n <= 'Z') else n for
n in
string])
except TypeError:
return None
result = rotX('xyz', 2)
reverse_result = rotX(result, -2)
print(result)
print(reverse_result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.