Python-Ref > String manipulation > String basics > String formatting operations
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

String formatting operations

Howto format numbers, strings and other types into a final string.
Python has the ability to use special character sequences in strings as "templates" for insertion of other data types and their formating.
The special sequences are preceded with %. The same % is used as operator to fill the tempate wit values.
Expand/Shrink
  1   print "-- floats --"
  2   pi = 3.1415927
  3   print "float %f" % pi     # %f is used for floats
  4   print "float %.3f" % pi   # .3 means 3 decimal places
  5   print
  6   
  7   print "-- integers --"
  8   print "integer %d" % 3     # %d is used for integers
  9   print "integer %3d" % 3    # number is of min length of 3, precede i with spaces
 10   print "integer %03d" % 3   # the same, but prepend zeros
 11   print
 12   
 13   print "-- integers in other forms --"
 14   print "hexadecimal %x" % 200   # hexadecimal lowercase
 15   print "hexadecimal %X" % 160   # hexadecimal uppercase
 16   print "octal %o" % 200   # octal
 17   print
 18   
 19   print "-- mixed content --"
 20   # the template might be stored in a variable
 21   template = "%d days till %s"   # %d is used for integers, %s for strings
 22   
 23   print template
 24   print template % (3, "Xmass")
 25   
 26   res = template % (100, "semestr end")
 27   print res
stdout:
-- floats --
float 3.141593
float 3.142

-- integers --
integer 3
integer   3
integer 003

-- integers in other forms --
hexadecimal c8
hexadecimal A0
octal 310

-- mixed content --
%d days till %s
3 days till Xmass
100 days till semestr end
Doba běhu: 14.0 ms
The template string might be either printed as is or with all the references expanded (filled). Otherwise an error will occur.
Expand/Shrink
  1   print "%d days till %s" % 4
stderr:
Traceback (most recent call last):
  File "str_basics2-2.py", line 2, in <module>
    print "%d days till %s" % 4
TypeError: not enough arguments for format string
Doba běhu: 13.6 ms
The % operator has a high preference and therefor care has to be taken when using results of arithmetic operations as its arguments.
In the better of the wrong cases, one gets an error.
Expand/Shrink
  1   print "float %f" % 3.14/5   # '%' is first, '/' second
stderr:
Traceback (most recent call last):
  File "str_basics2-3.py", line 2, in <module>
    print "float %f" % 3.14/5   # '%' is first, '/' second
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Doba běhu: 13.9 ms
In the worse one, completely uncalled for result is obtained.
Expand/Shrink
  1   print "float %f" % 3.14*5  # first '%' then '*'
stdout:
float 3.140000float 3.140000float 3.140000float 3.140000float 3.140000
Doba běhu: 13.6 ms
In this case, brackets are used to change the precedence rules.
Expand/Shrink
  1   print "float %f" % (3.14*5)   # brackets save the day
stdout:
float 15.700000
Doba běhu: 14.0 ms