水平翻转类似矩阵的字符串

Zai*_*nek 0 python string reverse

该函数的目标是水平翻转类似矩阵的字符串。

例如,具有 2 行和 3 列的字符串:“100010001”将如下所示:

1 0 0
0 1 0
0 0 1
Run Code Online (Sandbox Code Playgroud)

但翻转后应该看起来像:

0 0 1
0 1 0
1 0 0
Run Code Online (Sandbox Code Playgroud)

因此该函数将返回以下输出:“001010100”

需要注意的是,我不能使用列表或数组。只有字符串。

我相信我编写的当前代码应该可以工作,但是它返回一个空字符串。

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
Run Code Online (Sandbox Code Playgroud)

这再次返回一个空字符串。知道问题是什么吗?

Fog*_*ird 5

用于[::-1]反转图像的每一行。

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'
Run Code Online (Sandbox Code Playgroud)