2

lets say the variable "info" has the following string:

abc: 234234
aadfa: 235345
bcsd: 992

In python, what is the simplest way to format "info" to:

abc:    234234
aadfa:  235345
bcsd:   992
1
  • 3
    Can you show us what you have tried so far? I am pretty sure you need to loop over the labels, find the maximum length, and the loop over the labels again, padding them with sufficient spaces. Commented Apr 6, 2013 at 1:33

3 Answers 3

2

This will work:

>>> s = """abc: 234234
... aadfa: 235345
... bcsd: 992"""
>>> print s
abc: 234234
aadfa: 235345
bcsd: 992

Now we can split on the new line and the space to get each item per line:

>>> pairs = [x.split() for x in s.split('\n') ]
>>> pairs
[['abc:', ' 234234'], ['aadfa:', ' 235345'], ['bcsd:', ' 992']]

And now format each string:

>>> for pair in pairs:
...     print '{0:10} {1}'.format(pair[0], pair[1])
...
abc:        234234
aadfa:      235345
bcsd:       992

Note how we use {0:10} in the string formatting? That just means to format that argument with 10 characters.

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

Comments

1

Stealing @JoshSmeaton's variable name:

>>> pairs = map(str.split, text.splitlines())
>>> max_len = max(len(pair[0]) for pair in pairs)
>>> info = '\n'.join('{key:<{indent}}{val}'.format(key=k,
                                                   indent=max_len + 2,
                                                   val=v) for k, v in pairs)
>>> print info
abc:    234234
aadfa:  235345
bcsd:   992

Comments

0

Hope the following code helps.

>>> import math
>>> info = ["abc: 234234", "aadfa: 235345", "bcsd: 992"]
>>> info = [item.split() for item in info]
>>> maxlen = max([len(item[0]) for item in info])
>>> maxlen = math.ceil(maxlen/8.0)*8
>>> info = [item[0]+" "*(maxlen-len(item[0]))+item[1] for item in info]

You can control how the final length is made.

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.