Python string format example, python string example
Let's look at the code first.
#!/usr/bin/env python#-*- coding: utf-8 -*-__author__ = 'jiang'__creattime__ = '2015/10/31 23:40'width = input('please enter width:')price_width = 10item_width = width - price_widthheader_format = '%-*s%*s'format = '%-*s%*.2f'print '=' * widthprint header_format % (item_width,'Item',price_width,'Price')print '-' * widthprint format % (item_width,'Apples',price_width,0.4)print format % (item_width,'Pears',price_width,0.5)print format % (item_width,'Cantaloupes',price_width,1.92)print format % (item_width,'Dried Apricots(16 oz.)',price_width,8)print format % (item_width,'Prunes(4 lbs)',price_width,12)print '=' * width
OK. Let's see what it looks like.
==================================================Item Price--------------------------------------------------Apples 0.40Pears 0.50Cantaloupes 1.92Dried Apricots(16 oz.) 8.00Prunes(4 lbs) 12.00==================================================
It looks okay, but there is a problem. Try to make it bigger when you assign a value to width. If you assign a value too small, for example, 20, the price on the right will not be aligned. If you are interested, you can run one side of the Code.
Let's talk about several key points. Head_format = '%-* S % * s'. The string format operator % is followed by "s" to indicate that you can use str to format any python object. '-' Indicates the left alignment. '*' Indicates the width and precision of fields that can be received.
The following is the string format conversion type. You can check it.
Conversion Type meaning d, I-Signed decimal integer o unsigned octal u unsigned decimal x unsigned hexadecimal (lower case) X unsigned hexadecimal (upper case) e scientific Notation: Floating Point Number (lower case) E scientific Notation: Floating Point Number (upper case) f, F decimal floating point number r string (use repr to convert any python object) s string (use str to convert any python object)
You can search for more String Conversion types online.
Simple conversion:
>>>'Price of eggs : $%d' % 42'Price of eggs : $42'>>>from math import pi>>>'Pi : %f...' % piPi : 3.141593...>>>'my age is %s ' % 42L'my age is 42'>>>'my age is %r' % 42L'my age is 42L'
You can search for the differences between str and repr. I will not go into details here.
Click here to communicate with me