Is there a pythonic way to join a string in a loop to create a block of text?
Example:
for x in range(4):
content = f'{x}[block]'
content+content
print(content)
Desired outcome:
0[block]
1[block]
2[block]
3[block]
Is there a pythonic way to join a string in a loop to create a block of text?
Example:
for x in range(4):
content = f'{x}[block]'
content+content
print(content)
Desired outcome:
0[block]
1[block]
2[block]
3[block]
You could use str.join()
with a generator expression to join your block strings by newlines:
print("\n".join(f"{x}[block]" for x in range(4)))
Or for faster performance, use a list comprehension instead:
print("\n".join([f"{x}[block]" for x in range(4)]))
See this answer for more information on why the second approach is faster than the first
Additionally, you could also append each block string to a list and join them at the end:
blocks = []
for x in range(4):
blocks.append(f"{x}[block]")
print("\n".join(blocks))
If we want to simply print each block string without joining by newlines, we can make use of the sep
keyword from print()
:
print(*(f"{x}[block]" for x in range(4)), sep="\n")
Output:
0[block]
1[block]
2[block]
3[block]