Python- Adding a specified width to strings

孤街醉人 提交于 2019-12-01 19:40:42

In Python2.6 or later, you could use the str.format method:

with open('random_text.txt', 'w') as f:
    f.write('{0:6}{1:6}{2:4}'.format('Atom','word','next'))

yields a file random_text.txt with contents

Atom  word  next

The number following the colon indicate the width. For example, {0:6} formats the 0-th argument, 'Atom', into a string with a width of 6. The string could be "right-justified" by using the format {0:>6}, and there are other options as well.

string = "atom"
width = 6
field = "{0:<{1}}".format(string[:width], width)

This will truncate string to width if necessary, since you can't actually specify the max width in format string, just the minimum width that the field will be padded to.

Use str.format, define field widths (:<width>) and expand your data (*<list>).

>>> columns = ['aaaa', 'bbbbbb', 'ccc']
>>> print '{:4}{:6}{:3}'.format(*columns)

Additionally, you can abuse the precision .8 to trim a string field. The first 8 sets the minimum field width.

>>> print '{:8.8}'.format('Too long for this field')
Too long
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!