format my string

How many ways are there to include a variable in a string?

The one I am most familiar with:

print "This string includes %s and %s" %("x", "y")
# This string includes x and y

Use %s with numbers:

print "This string includes %s and %s" %(120.06, 125)
# This string includes 120.06 and 125

Use %d instead with numbers:

print "This string includes %d and %d" %(120.06, 125)
# Note rounding
# This string includes 120 and 125

Use .format() to include decimal places:

print "This string includes {0} and {1}".format(120.06, 125)
# This string includes 120.06 and 125

Mod both numbers with {:.2f} to be decimals:

print "This string includes {0:.2f} and {1:.2f}".format(120.06, 125)

Call second variable first:

# Note that the second var (125) is called first
print "This string includes {1:.2f} and {0:.2f}".format(120.06, 125)
#This string includes 125.00 and 120.06

Use .format(**vars()):

var1, var2 = "x", "y"
print "This string includes {var1} and {var2}".format(**vars())

Some cool formatting options here and here:

# Padding left
'{:>20}'.format('String padding')
'      String padding'

# format the padded spaces
'{:_>20}'.format('Sring padding')
'_______Sring padding'

# Padding right with format
'{:_<20}'.format('Sring padding')
'Sring padding_______'

# Pad left, pad right, format
'{:_^20}'.format('Sring padding')
'___Sring padding____'

# Pad left, pad right, truncate, format
'{:_^20.5}'.format('Sring padding')
'_______Sring________'

results matching ""

    No results matching ""