String formatting:
string Formatting:%:%s formatted as string [HTML] view plain copy>>> format ="Hello,%s.%s enough for ya?">>> values = (' World',' Hot') >>>PrintFormat%values Hello, world. Hot Enough forya? %F formatted as real number (floating point) [HTML] view plain copy>>> format ="Pi with three decimals:%.3f"//retain 3 significant digits after the decimal point>>> fromMathImportpi//value of the import Pi>>>PrintFormat%Pi Pi with three decimals:3.142template string: keyword parameter (substitute): Word substitution [HTML] view plain copy>>> fromStringImportTemplate>>> s = Template ('$x, gloriout $x!') >>> S.substitute (x ='Slurm') 'Slurm, Gloriout slurm!'Word letter substitution [HTML] view plain copy>>> fromStringImportTemplate>>> s = Template ("It ' s ${x}tastic!") >>> S.substitute (x ='Slurm') "It ' s slurmtastic!"Insert $ symbol with $$ [HTML] view plain copy>>> fromStringImportTemplate>>> s = Template ("Make $ selling $x!") >>> S.substitute (x ='Slurm') 'Make $ selling slurm!'dictionary variable provides value [HTML] view plain copy>>> fromStringImportTemplate>>> s = Template ('A $thing must never $action') >>> d = {} >>> d['thing'] ='Gentleman'>>> d['Action'] ='Show his socks'>>>S.substitute (d)'A gentleman must never show his socks'with*as field width or precision [HTML] view plain copy>>>'%.*s'% (5,'Guido van Rossum') 'Guido'Conversion Flags:-: Align Left+: Add the Sign "" before the value is converted: A positive number preserves the space 0: The conversion value is not enough for 0 to populate the [HTML] view plain copy>>> pi = 3.1415 >>>'%010.2f'%Pi'0000003.14'>>>'%-10.2f'%Pi'3.14'>>>'%10.2f'%Pi'3.14'>>>'% 10.2f'%Pi'3.14'>>>'%+10.2f'%Pi'+3.14'
string formatting example [HTML] View plain copy width= Input ('Please enter width:') Price_width= 10Item_width= width-price_width Header_format='%-*s%*s'format='%-*s%*.2f' Print '='*widthPrintHeader_format% (Item_width,'Item', Price_width,' Price') Print '-'*widthPrintFormat% (Item_width,'Apples', Price_width, 0.4) PrintFormat% (Item_width,'Pears', Price_width, 0.5) PrintFormat% (Item_width,'cantaloupes', Price_width, 1.92) PrintFormat% (Item_width,'dried apricots (oz.)', Price_width, 8) PrintFormat% (Item_width,'Prunes (4 lbs.)', Price_width, 12The results show: [HTML] View plain copy Please enter width:35 ===================================Item Price-----------------------------------Apples0.40Pears0.50cantaloupes1.92Dried apricots (Oz.) 8.00Prunes (4 lbs.) 12.00
Python: String Formatting