简体   繁体   中英

python string manipulation with format command

I have the follow python code but i dont know what it is doing, can someone help me understand what it is doing please? I've googled but i dont know what im searching for..

single_line = "1562661"
single_line = '{:<07}'.format(single_line)

Straight from the docs :

Padding and aligning strings

By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length.

Unfortunately the default alignment differs between old and new style formatting. The old style defaults to right aligned while for new style it's left.

Example:

single_line = "123"
single_line = '{:<07}'.format(single_line)

Results in :

'1230000'

So this particular code of your is used to add extra spaces if your string size exceeds 7.

Example 1

single_line = "1562661"
single_line = '{:<07}'.format(single_line)

for ex: This code above will give us

'1562661'

Example 2

single_line = "1562661"
single_line = '{:<10}'.format(single_line)

'1562661   '(This will be genererated by the code above with 3 trailing spaces)

Example 3:

single_line = "1562661"
single_line = '{:>10}'.format(single_line)

'   1562661'(This will be genererated by the code above with 3 leading spaces)

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM