1

If I have these names:

bob = "Bob 1"

james = "James 2"

longname = "longname 3"

And priting these gives me:

Bob 1

James 2

longname 3

How can I make sure that the numbers would be aligned (without using \t or tabs or anything)? Like this:

Bob 1

James 2

longname3

1 Answer 1

5

This is a good use for a format string, which can specify a width for a field to be filled with a character (including spaces). But, you'll have to split() your strings first if they're in the format at the top of the post. For example:

"{: <10}{}".format(*bob.split())
# output: 'Bob       1'

The < means left align, and the space before it is the character that will be used to "fill" the "emtpy" part of that number of characters. Doesn't have to be spaces. 10 is the number of spaces and the : is just to prevent it from thinking that <10 is supposed to be the name of the argument to insert here.

Based on your example, it looks like you want the width to be based on the longest name. In which case you don't want to hardcode 10 like I just did. Instead you want to get the longest length. Here's a better example:

names_and_nums = [x.split() for x in (bob, james, longname)]
longest_length = max(len(name) for (name, num) in names_and_nums)
format_str = "{: <" + str(longest_length) + "}{}"
for name, num in names_and_nums:
    print(format_str.format(name,  num))

See: Format specification docs

Sign up to request clarification or add additional context in comments.

3 Comments

You don't need to use that str(longest_length); you can use formatting to build that. Or even use a recursive format: {:<{}}{}'.format(name, longest_length, num). (Although I'd probably use manual numbering at that point.)
I was on the fence about using '{{: <{}}}{{}}'.format(longest_length) due to readability and the need to edit all the braces if you go back and forth between a constant or variable format. The recursive format idea is nice.
One of the things I still use %-formatting for is creating {}-format strings: '{:<%d}{}' % (longest_length,) is a lot easier to read… But for teaching a novice, it may not be a good idea to spring both kinds of formatting on him in a single answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.