'Flipping a matrix-like string horizontally

The goal of this function is to flip a matrix-like string horizontally.

For example the string: '100010001' with 2 rows and three columns would look like:

1 0 0
0 1 0
0 0 1

but when flipped should look like:

0 0 1
0 1 0
1 0 0

So the function would return the following output: '001010100'

The caveat, I cannot use lists or arrays. only strings.

The current code I have written up, I believe, should work, however it is returning an empty string.

def flip_horizontal(image, rows, column):

   horizontal_image = ''
   for i in range(rows):

       #This should slice the image string, and map image(the last element in the 
       #column : to the first element of the column) onto horizontal_image.
       #this will repeat for the given amount of rows

       horizontal_image = horizontal_image + image[(i+1)*column-1:i*column]
    
   return horizontal_image

Again this returns an empty string. Any clue what the issue is?



Solution 1:[1]

Use [::-1] to reverse each row of the image.

def flip(im, w):
    return ''.join(im[i:i+w][::-1] for i in range(0, len(im), w))

>>> im = '100010001'
>>> flip(im, 3)
'001010100'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FogleBird