Search code examples
pythonstringmirror

Mirroring a string of text using Python


I am trying to write code to mirror a string within python. I assumed it was similar to mirroring an image or a sound however I cannot get past the loop. The input and output should both be a string.

def mirror(text):
  mirrorPoint=(len(text)/2)
  for i in range(0,mirrorPoint):
    text=text[mirrorPoint]
  return text+''.join(string(text))
print mirror('text')

I am not sure if this is right, but it gets caught on the second to last line of text.

If the input was 'abcd' the output should yield 'abba'.


Solution

  • If I understand you correctly:

    def mirror(text):
        mirror_point = int(len(text)/2)
        res = text[:mirror_point] # Get Slice of Text
        return res + res[::-1] # Add Slice Plus Reverse of the Slice
    print mirror( 'abcd')
    

    In you code:

    mirrorPoint = (len(text)/2) will be a float so when passed to range it will not work as range needs an integer.

    ''.join(string(text)) , you would use str(text) if you were going to cast to a str but text is already a string so there is no need to cast.

    text = text[mirrorPoint] keeps changing the value of text so you will get an index error, if you wanted to store a string variable outside the loop like res = "", you could then use res += text[i] where text[i] is each character you want to add

    Using your own code:

    def mirror(text):
        res = ""
        mirrorPoint = int(len(text)/2)
        for i in range(mirrorPoint):
            res += text[i]
        return text[:mirrorPoint] + res[::-1]
    

    To handle uneven length strings we need to add 1 to mirror_point if the string is an odd length:

    def mirror(text):
        mirror_point = int(len(text) / 2)
        if mirror_point % 2 == 0:
            res = text[:mirror_point]
        else:
            res = text[:mirror_point+1]
        return res + res[::-1]