Skip to content

Latest commit

 

History

History
executable file
·
52 lines (32 loc) · 1.12 KB

File metadata and controls

executable file
·
52 lines (32 loc) · 1.12 KB

Formatting strings and output

Examples in Python 3

"""
Format strings for fancier output
"""
# Add variable values to a string
x = "{0} ants are more than {1} elephants".format("Five", 4)
print(x)

x = "Five"
y = 4
print("{0} ants are more than {1} elephants".format(x, y))

# With named parameters
print("My name is {name} and I am {age} years old.".format(age=18, name="Mumintrollet"))

# Add thousands separator
print("{:,}".format(1000000))

# Fixed floating point
print("{:.2f}".format(1.2345))

print("{:.3f}".format(42))

# Fixed character width
print("{0:10}{1:10}".format("Hello", "World"))

Reference and read more

String Formatting

Format String Syntax

str.format()

Fancier Output Formatting

Revision history

2014-07-16 (sylvanas) PA1 First try.