Python - String Formatting Expression Basics

Introduction

Python defines the % binary operator to work on strings.

When applied to strings, the % operator formats values as strings according to a format definition.

The % operator substitutes multiple string at once.

To format strings:

  • On the left of the % operator, provide a format string using conversion targets, such as %d.
  • On the right of the % operator, provide the object.

In the following code, the integer 1 replaces the %d in the format string on the left.

The string 'dead' replaces the %s.

Demo

print( 'That is %d %s bird!' % (1, 'dead') )             # Format expression

Result

A few more examples:

Demo

exclamation = 'Hi' 
print( '%s!' % exclamation )         # String substitution 
# from  www.jav  a 2  s  .c  o  m
print( '%d %s %g you' % (1, 'test', 4.0) )               # Type-specific substitutions 
print( '%s -- %s -- %s' % (42, 3.14159, [1, 2, 3]) )     # All types match a %s target

Result

The first example here inserts the string 'Hi' into the target on the left, replacing the %s marker.

In the second example, three values are inserted into the target string.

Related Topic