I know this is an old thread but I'd like to propose a more elegant solution that "fails gracefully" when the combined text's length exceeds the desired length.
def align_left_right(left: str, right: str, total_len: int = 80) -> str:
left_size = max(0, total_len - len(right) - 1) # -1 to account for the space
return format(left, f"<{left_size}") + " " + right
def main():
print("1.", align_left_right("|left", "right|"))
print("2.", align_left_right("|", "right|"))
print("3.", align_left_right("|left", "|"))
print("4.", align_left_right("|left", "right|", total_len=20))
print("5.", align_left_right("|left", "a longer text that doesn't fit|", total_len=20))
if __name__ == "__main__":
main()
output :
1. |left right|
2. | right|
3. |left |
4. |left right|
5. |left a longer text that doesn't fit|
You could make a more full-fledged version using textwrap.shorten
to keep the total size constant even when one or both strings are too long.