Reputation: 283
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
Upvotes: 2
Views: 2481
Reputation: 48720
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.
Upvotes: 2
Reputation: 133554
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
Upvotes: 1
Reputation: 3555
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.
Upvotes: 0