• + 0 comments

    I did this a liltte differently. First difference being that I made an empty 2D-list of the matrix from the given size. Then I place each character in the correct position using math x+(n*y). And finally join with a regex subsutition. Also, \w & \W are great replacements for all of that text the rest of you have.

    import re
    first_multiple_input = input().rstrip().split()
    n = int(first_multiple_input[0])
    m = int(first_multiple_input[1])
    
    regex = re.compile(r'(?<=\w)([\W]+)(?=\w)')
    matrix = [None] * n * m
    
    for x in range(n):
        matrix_item = [x for x in input()]
        for y in range(m):
            matrix[x+(n*y)] = matrix_item[y]
     
    print(re.sub(regex, ' ', ''.join(matrix)))