0

Let's say I have an arbitrary number of strings of the same length, e.g.:

'01'
'02'
'03'

And I need to format them into "one line grid" (separated with spaces) with fixed length. So, I'd like to do something like this:

>>'{some expression, 15, left}'.format(['01','02','03'])
'01 02 03       '

>>'{some expression, 15, right}'.format(['01','02','03'])
'       01 02 03'

Is it possible to do it like this just with format or in some other elegant way?

I want to use Python 3.

2
  • How are the arbitrary strings read, from a file or you already have a reference/variable? Commented Jun 22, 2016 at 9:16
  • @MosesKoledoye They're meant to be read from a variable. Commented Jun 22, 2016 at 10:02

2 Answers 2

2

This is an apt solution to your problem that uses the inbuilt function format.

list = ['01','02','03']
list1=' '.join(list)
list_right='{:>15}'.format(list1)   #right 
list_left='{:<15}'.format(list1)    #left
print (list_right)

Here, < forces the field to be left-aligned within the available space (this is the default for most objects) while, > forces the field to be right-aligned within the available space (this is the default for numbers).

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

2 Comments

Thank you! Could you just correct the last print (I've specified python3, where print needs braces ), comments to Python format (to make it possible just to copy and launch the code) and separate the values just with space instead of a dash? I understand the code, but I think these changes will make it more useful for beginners, because it will fit completely to my question.
Corrected, Thank you!
1

This solution employs a lambda function and is more flexible -

list123 = ['01','02','03']
x=15                                     #limiting factor for str length
s123 = ' '.join(list123)                 #list elements become a str seperated by a space
s_space= lambda x:(x-len(s123))*' '      #store x-len(s123) spaces
s_left=s_space(x) +s123
s_right=s123 + s_space(x)
print(s_left)

Output : ' 01 02 03'

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.