[英]invalid syntax in returning a list in python
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)此代码显示错误 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{|
将打印
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.此外,使用
''.join(your_list)
将允许将结果列表合并为一个字符串,以便您的 function 返回它给出的相同类型。
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):顺便说一句,如果您的初始目标是实现像 rot13 (在您的情况下为 rot2)这样的字符旋转,您可以使用更智能的 function 也只处理字母字符以使 output 可移植(仅可打印字符):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.