Need help with custom string formatter

MRAB python at mrabarnett.plus.com
Sat Nov 5 13:15:52 EDT 2022


On 2022-11-05 11:07, Stefan Ram wrote:
> Robert Latest <boblatest at yahoo.com> writes:
>>>result += ' ' *( length - len( result ))
>>Nice, I didn't know that one could multiply strings by negative numbers without
>>error.
> 
>    Thanks, but today I thought that maybe there might
>    be a solution for getting a field of a fixed length
>    that is even shorter. It uses Python's string
>    formatting, here in the form of an "f" string.
> 
>    main.py
> 
> def f( result, length ):
>      # get a field with the given length from the string "result"
>      # - as used in postings from october
>      result = result[ :length ]
>      result += ' ' *( length - len( result ))

That can be done more compactly as:

      result = result[ : length].ljust(length)

>      return result
> 
[snip]




More information about the Python-list mailing list