Python string format method

Format a string

String formatting is done with the string formatting operator, the percent (%) sign.

The following code formats a integer value into a sentence.

      
userCount = 6 
print "Users connected: %d" % (userCount, )     

The code above generates the following result.

We can use the string appending to achieve the same result, but string format sign % gives us more functionalities.


uid = "sa" 
pwd = "secret" 
print pwd + " is not a good password for " + uid    
print "%s is not a good password for %s" % (pwd, uid)    

The code above generates the following result.

The right operand of the formatting operator may be anything; if it is either a tuple or a dictionary, it is given special treatment. If the right operand is a tuple, each of its elements is formatted separately, and you need a conversion specifier for each of the values.

If you write the tuple to be converted as part of the conversion expression, you must enclose it in parentheses to avoid confusing Python:


'%s plus %s equals %s' % (1, 1, 2) 
'%s plus %s equals %s' % 1, 1, 2 # Lacks parentheses! 

The code above generates the following result.

format specifier

The following table covers the conversion specifier used by Python.

Format operator


%        marks the beginning of the conversion

Conversion flags


Conversion flags             optional/*from   www  .ja  va2  s.c  o m*/
                             - indicates left a alignment
                             + indicates that a sign should appear precede the value
                             " " (space) indicates that a space should precede the positive number
                             0 indicates zero padding

Minimum field width


minimum field width          optional
                             The final output would be at least this wide. 
                             * indicates to read the width from the tuple.

Precision


. precision                  optional
                             indicates the number of decimal places a real number should have
                             or the maximum length for a string value being converted
                             * indicates to read the width from tuple




















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary