'Python: Why cannot I assign printed value to variable?

The problem is I cannot assign printed value to variable. When I comment last line(print(''.join(padded_strings)) and uncomment last three lines of code I receive empty string. Do you know how to deal with the issue ?

import random

DICE_ART3 = {
    1: """
    ┌─────────┐
    │         │
    │    ●    │
    │         │
    └─────────┘
    """,
    2: """
    ┌─────────┐
    │ ●       │
    │         │
    │       ● │
    └─────────┘
    """,
    }

def roll_dice(n_dice=5):
    my_dices = []
    for n in range(n_dice):
        dice =[random.randint(1,2)]
        my_dices.extend(dice)

    my_dices2 = []
    for n in range(n_dice):
        dice_str = [DICE_ART3[my_dices[n]]]
        my_dices2.extend(dice_str)

    strings_by_column = [s.split('\n') for s in my_dices2]
    strings_by_line = zip(*strings_by_column)
    max_length_by_column = [
        max([len(s) for s in col_strings])
        for col_strings in strings_by_column
    ]
    for parts in strings_by_line:
        # Pad strings in each column so they are the same length
        padded_strings = [
            parts[i].ljust(max_length_by_column[i])
            for i in range(len(parts))
        ]

        print(''.join(padded_strings))
        # output = ''.join(padded_strings)
    #print(output)
    #return(output)

roll_dice(5)


Solution 1:[1]

You only store the last line in output. Gather everything in a list. Here is the changed last part of the function.

result = []
for parts in strings_by_line:
    # Pad strings in each column so they are the same length
    padded_strings = [
        parts[i].ljust(max_length_by_column[i])
        for i in range(len(parts))
    ]
    output = ''.join(padded_strings)
    result.append(output)
return result

Then you can receive the list in the caller and print it.

for line in roll_dice(5):
    print(line)

Alternative you can gather everything in a list and return a string joined with newline characters.

return '\n'.join(result)

Calling the function and printing the result:

print(roll_dice(5))

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 Matthias