2

So I have a problem I know can be solved with string formatting but I really don't know where to start. What I want to do is create a list that is padded so that there is n number of characters before a comma as in the list below.

 1148,
   39,
  365,
    6,
56524,

Cheers and thanks for your help :)

3 Answers 3

4

The most straight-forward way is to use the str.rjust() function. For example:

your_list = [1148, 39, 365, 6, 56524]

for element in your_list:
    print(str(element).rjust(5))

And you get:

 1148
   39
  365
    6
56524

There are also str.center() and str.ljust() for string justification in other directions.

But you can also do it via formatting:

your_list = [1148, 39, 365, 6, 56524]

for element in your_list:
    print("{:>5}".format(element))
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I screwed up, what I also should have said is that I'm writing rows to a csv file row by row not from a list. So what I need is for the first coma in each row to line up despite the first integer being different lengths.
You can use the above technique to 'pad' the first element of each of your rows - you just need to find out the maximum length (largest value) upfront. So loop through your data first and find the largest value, then get its character length (len(str(largest_value))) and then use that number for str.rjust() when padding the first element. Don't worry about comas and such - use the built-in csv module to do your bidding when it comes to generating the actual CSV structure.
2

See Format Specification Mini-Language.

You are looking for something like "{:5d},".format(i) where i is the integer to be printed with a width of 5.

For a variable width: "{:{}d},".format(i, width).

Comments

0

Assuming you know what n is you can do: '{:>n}'.format(number)

So if you have a list of integers and wanted to format it as above you could do:

numbers = [1148, 39, 365, 6, 56524]
result = '\n'.join(('{:>5},'.format(x) for x in numbers))

Comments

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.