Home > Article > Backend Development > How can I achieve fixed-width alignment of printed strings in Python?
In programming, it's often desirable to align strings in fixed columns for clarity and visual organization. This article explores how to achieve this using advanced formatting techniques in Python.
Consider the following code that calculates the frequency of all permutations in a given string:
# Original code to generate permutations ... # Printing results unique = sorted(set(el)) for prefix in unique: if prefix != "": print("value ", prefix, "- num of occurrences = ", string.count(str(prefix)))
However, the output may appear misaligned due to varying string lengths:
value a - num of occurrences = 1 value ab - num of occurrences = 1 value abc - num of occurrences = 1 value b - num of occurrences = 1 value bc - num of occurrences = 1 value bcd - num of occurrences = 1 value c - num of occurrences = 1 value cd - num of occurrences = 1 value d - num of occurrences = 1
To align the output, we can utilize the str.format method with specific format specifiers:
# Using str.format for alignment print("{0: <5}".format("value ") + "{1: >15}".format(prefix) + "- num of occurrences = " + "{2: <5}".format(string.count(str(prefix))))
Format Specifiers:
Edit 1: The "0" in "{0: <5}" refers to the index of the argument passed to str.format().
Edit 2: Python 3 introduces f-strings as a concise alternative to str.format:
# Using f-strings for alignment print(f"{'value ':<5}" + f"{prefix:>15}" + "- num of occurrences = " + f"{string.count(str(prefix)):<5}")</p>
Advantages:
The above is the detailed content of How can I achieve fixed-width alignment of printed strings in Python?. For more information, please follow other related articles on the PHP Chinese website!