Writing/parsing a fixed width file using Python

前端 未结 8 1739
清歌不尽
清歌不尽 2020-12-14 11:01

I\'m a newbie to Python and I\'m looking at using it to write some hairy EDI stuff that our supplier requires.

Basically they need an 80-character fixed width text f

8条回答
  •  盖世英雄少女心
    2020-12-14 11:30

    You don't need to assign to slices, just build the string using % formatting.

    An example with a fixed format for 3 data items:

    >>> fmt="%4s%10s%10s"
    >>> fmt % (1,"ONE",2)
    '   1       ONE         2'
    >>> 
    

    Same thing, field width supplied with the data:

    >>> fmt2 = "%*s%*s%*s"
    >>> fmt2 % (4,1, 10,"ONE", 10,2)
    '   1       ONE         2'
    >>> 
    

    Separating data and field widths, and using zip() and str.join() tricks:

    >>> widths=(4,10,10)
    >>> items=(1,"ONE",2)
    >>> "".join("%*s" % i for i in zip(widths, items))
    '   1       ONE         2'
    >>> 
    

提交回复
热议问题