Interpolate/Resize Ascii Art in Python?

I want to resize some ascii art. Say it looks like this:

..K
.T.
.A.

I want to upscale it, by some number n, so it will look like this (n=2)

....KK
....KK
..TT..
..TT..
..AA..
..AA..

One way I thought about doing this was to convert the text into a matrix of their ascii values and use some interpolation function to resize the matrix, and convert it back to text to achieve the desired result, but I have not been able to find a function that will do that for me.

What is the easiest way to do this. If it makes it simpler, you can assume that n is always 4. (Because in my current situation this is the scale I need)

1

1 Answer

Assuming you have a file test.txt with following content:

..K
.T.
.A.

The following code will read the file and prodcue an output file test_out.txt which contains horizontally and vertically multiplied characters, depending what you specify for N:

N = 4

with open('test.txt', 'r') as f:
    with open('test_out.txt', 'w') as out_f:
        for line in f:
            # Repeat characters N times horizontally
            output = "".join([N * c for c in line.strip()])

            # Repeat lines N times vertically
            for _ in range(N):
                out_f.write(output + '\n')

Output (test_out.txt) for N = 2:

....KK
....KK
..TT..
..TT..
..AA..
..AA..

Output (test_out.txt) for N = 4:

........KKKK
........KKKK
........KKKK
........KKKK
....TTTT....
....TTTT....
....TTTT....
....TTTT....
....AAAA....
....AAAA....
....AAAA....
....AAAA....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest