Open topic with navigation
String Formatting
Use Python’s string.format method for a variety of string formatting tasks. This is the preferred way over the older % string format operator. String formatting makes it easy to embed variable data into constant text. The example script below shows different ways the string.format method is used:
# http://docs.python.org/3.8/library/string.html#format-string-syntax
import math
import viz
# Specify fields using positional arguments
print('{} {} {}'.format(1,2,3))
# Output: "1 2 3"
# Specify fields using numbered positional arguments
print('{2} {1} {0} {2}'.format(1,2,3))
# Output: "3 2 1 3"
# Specify fields using keyword arguments
print('{a} {b} {c} {a}'.format(c=3,b=2,a=1))
# Output: "1 2 3 1"
# Specify fields using keyword arguments from dictionary
values = { 'name': 'Arthur', 'age': 42 }
print('{name} {age}'.format(**values))
# Output: "Arthur 42"
# Specify fields as attributes of objects
data = viz.Data(name='Arthur', age=42)
print('{person.name} {person.age}'.format(person=data))
# Output: "Arthur 42"
# Braces can be doubled to insert a literal brace character
print('{{ {} }}'.format('hello'))
# Output: "{ hello }"
# Display 5 digits after decimal point
print('{:.5f}'.format( math.pi ))
# Output: "3.14159"
# Use thousands separator for larger numbers
print('{:,d}'.format( 10000 ))
# Output: "10,000"
# Combine thousands separator with digit precision
print('{:,.1f}'.format( 10000 ))
# Output: "10,000.0"
# Force plus/minus sign on numbers
print('{:+.5f}'.format( math.pi ))
# Output: "+3.14159"
# Display number integers in various formats
print('binary: {value:b}, hex: {value:x}, HEX: {value:X}, octal: {value:o}'.format(value=42))
# Output: "binary: 101010, hex: 2a, HEX: 2A, octal: 52"
# Pad value to take up at least 5 spaces
print('{:5d}'.format( 5 ))
# Output: " 5"
# Pad value with leading zeros
print('{:05d}'.format( 5 ))
# Output: "00005"
# Pad value and align to the left
print('{:<5}.'.format('a'))
# Output: "a ."
# Pad value and align to the right
print('{:>5}.'.format('a'))
# Output: " a."
# Pad value and align to the center
print('{:^5}.'.format('a'))
# Output: " a ."
# Specify custom characters for padding
print('{:*>5}'.format('a'))
# Output: "****a"
print('{:#<5}'.format('a'))
# Output: "a####"
print('{:-^5}'.format('a'))
# Output: "--a--"