[英]print the mirror image of string in Python3
I'm trying to develop function mirror() that takes a string and returns its mirror image but only if the mirror image can be represented using letter in the alphabet.我正在尝试开发 function mirror() ,它接受一个字符串并返回其镜像,但前提是镜像可以使用字母表中的字母表示。
>>>mirror('vow')
'wov'
>>>mirror('bed')
'INVALID'
My code doesn't give me correct answers.我的代码没有给我正确的答案。 Thanks for any tips!感谢您的任何提示!
def mirror(word):
a={'b':'d','d':'b', 'i':'i', 'o':'o','v':'v','w':'w','x':'x'}
res=''
for letter in word:
if letter in a:
res=res+a[letter]
return res
else:
return 'INVALID'
return res
The return res
in the if statement needs to be removed, the program currently exits if the first letter is a match and returns that. if 语句中的return res
需要删除,如果第一个字母匹配,则程序当前退出并返回。
This should work这应该工作
def mirror(word):
a={'b':'d','d':'b', 'i':'i', 'o':'o','v':'v','w':'w','x':'x'}
res=''
for letter in word:
if letter in a:
res += a[letter]
else:
return 'INVALID'
return res
print(mirror("bob"))
return will break out of your function so once it finds the first letter it will stop running. return 将突破您的 function 因此一旦找到第一个字母,它将停止运行。
I also changed我也变了
res=res+a[letter]
to....至....
res += a[letter]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.