Best way to print detailed info to console

Viewed 75

What is the best way to print detailed info to the console? I usually use f-strings for console output as for exampleprint(f"{data=}") is really handy. However i can't do join statements as the f-string expression part cannot include a backslash:

# This does not work
print(f"{'\n'.join(['1', '2', '3'])}")

Even if the backslash does work i feel like this is really messy because of the different types of quotation marks.

I can think of multiple ways to solve this issue, however they don't feel that clean:

Example code

data = [["1", "2", "3"], ["cat", "dog"], ["item1", "item2"]]

# Approach 1
print("Current data:\n\t{}".format("\n\t".join(["{} -> {}".format(i, " ".join(data[i])) for i in range(len(data))])))

# Approach 2
print("Current data:\n\t" + "\n\t".join(f"{i} -> " + " ".join(data[i]) for i in range(len(data))))

# Approach 3
s = "Current data:"
for i in range(len(data)):
    tmp = " ".join(data[i])
    s += f"\n\t{i} -> {tmp}"
print(s)

Output

Current data:
        0 -> 1 2 3
        1 -> cat dog
        2 -> item1 item2
Current data:
        0 -> 1 2 3
        1 -> cat dog
        2 -> item1 item2
Current data:
        0 -> 1 2 3
        1 -> cat dog
        2 -> item1 item2

Currently i usually use f-strings whenever i can, otherwise i'll use the first approach.

What is the best practice for this?

1 Answers

Here is a possible alternative solution:

print(*['Current data:',
        *map(lambda x: f'{x[0]} -> {" ".join(x[1])}', enumerate(data))],
      sep='\n\t')

Or:

print(*['Current data:',
        *map(' -> '.join, zip(map(str, range(len(data))), map(' '.join, data)))],
      sep='\n\t')

Output:

Current data:
    0 -> 1 2 3
    1 -> cat dog
    2 -> item1 item2
Related