Python mirrored string function

前端 未结 5 495
攒了一身酷
攒了一身酷 2021-01-16 12:45

I\'m trying to develop a function mirror() that takes a string and returns its mirrored string but only if the mirrored string can be represented using \"mirror

5条回答
  •  一生所求
    2021-01-16 13:37

    You can look up the replacement characters in a generator expression as you iterate over the string (in reverse). You can reassemble characters into a string with str.join. I suggest using the "Easier to Ask for Forgiveness than Permission" idiom to handle invalid characters (don't check up front if the character is valid, but instead use try and catch statements to handle the exception raised if it is not).

    def mirror(s):
        mir={'b':'d','d':'b','o':'o','p':'q','q':'p','v':'v','w':'w','x':'x'}
        try:
            return "".join(mir[c] for c in reversed(s))
        except KeyError:
            return "INVALID"
    

提交回复
热议问题