CSC111 Formatting String Example
--D. Thiebaut (talk) 16:57, 8 February 2015 (EST)
Source Code
# formatExo.py
# D. Thiebaut
# Demonstration of ways to format strings, ints, and floats
# in Python Version 3. Refer to Section 5.8.2 in Zelle for
# more information.
#
def version1():
name = "Alex"
age = 12
coef = 6.188888
print( "\nVersion 1" )
print( "name:", name, "age:", age, "coefficient:", coef, "/20" )
def version2():
name = "Alex"
age = 12
coef = 6.188888
print( "\nVersion 2" )
print( "name: {0:>10} age: {1:3} coefficient: {2:1.2f}/20".format(
name, age, coef ) )
def version3():
name1 = "Alex"
age1 = 12
coef1 = 6.188888
name2 = "Anastasia"
age2 = 22
coef2 = 8
print( "\nVersion 3" )
print( "name: {0:>10} age: {1:3} coefficient: {2:1.2f}/20".format(
name1, age1, coef1 ) )
print( "name: {0:>10} age: {1:3} coefficient: {2:1.2f}/20".format(
name2, age2, coef2 ) )
def version4():
name1 = "Alex"
age1 = 12
coef1 = 6.188888
name2 = "Anastasia"
age2 = 22
coef2 = 8
print( "\nVersion 4" )
print( "name: {0:<10} age: {1:3} coefficient: {2:1.2f}/20".format(
name1, age1, coef1 ) )
print( "name: {0:<10} age: {1:3} coefficient: {2:1.2f}/20".format(
name2, age2, coef2 ) )
version1()
version2()
version3()
version4()
Output
Version 1
name: Alex age: 12 coefficient: 6.188888 /20
Version 2
name: Alex age: 12 coefficient: 6.19/20
Version 3
name: Alex age: 12 coefficient: 6.19/20
name: Anastasia age: 22 coefficient: 8.00/20
Version 4
name: Alex age: 12 coefficient: 6.19/20
name: Anastasia age: 22 coefficient: 8.00/20