[Algorithm] Output Methods in Python
Ways to Print in Python
In Python, using f-strings is one of the easiest and most common ways to format and print your data.
f-strings
print(f"a = {a}\nb = {b}")
You can format your output as shown above.
If we assume a = 4 and b = 5, the output will look like this:
a = 4
b = 5
Repeated Output
print(word * number)
This is possible if word is a string and number is an integer.
The word will be repeated as many times as the number specifies.
For example, if word = "word" and number = 3, the output will be wordwordword.
If you want to include spaces between the repeated words, there are two main ways to do it:
1. Using .join()
print(" ".join(["word"] * number))
Using the join() function is a very intuitive way to handle repeated output with spaces.
2. Using the sep Argument in print()
print(*["word"] * number, sep=" ")
You can achieve the same result more concisely by using the sep (separator) argument of the print function along with the unpacking operator (*).