EX6
# In less formal terms, the replacement field can start with a field_name
# that specifies the object whose value is to be formatted and inserted
# into the output instead of the replacement field. The field_name is
# optionally followed by a conversion field, which is preceded by an
# exclamation point ‘!’, and a format_spec, which is preceded by a colon ‘:’.
# These specify a non-default format for the replacement value.
# Three conversion flags are currently supported: ‘!s’ which calls str() on the value,
# ‘!r’ which calls repr() and ‘!a’ which calls ascii().
# Some examples:
# “Harold’s a clever {0!s}” # Calls str() on the argument first
# “Bring out the holy {name!r}” # Calls repr() on the argument first
# “More {!a}” # Calls ascii() on the argument first
x = “There are {:d} types of people.” .format(10)
binary = “binary”
do_not = “don’t”
y = “Those who know {:s} and those who {:s}.”.format(binary, do_not)
print (x)
print (y)
print (“I said: {!r}.” .format(x))
print (“I also said: ‘{!s}’.” .format(y))
hilarious = False
joke_evaluation = “Isn’t that joke so funny?! %r”
print (joke_evaluation % hilarious)
#这个写法其实是:
#hilarious = False
#joke_evaluation = “Isn’t that joke so funny?! %r” % hilarious
#print joke_evaluation
#其中%r calls repr(), which represents False (bool) as “False” (string).
#转成3.0版的写法就是:
hilarious = False
joke_evaluation = “Isn’t that joke so funny?! {!r}” .format(hilarious)
print (joke_evaluation)
# %s和%r区别如例:
# test = “””hello,\nworld”””
# print “this is test1: %s” %test
# print “this is test2: %r” %test
# 输出:
# this is test1: hello,
# world
# this is test2: ‘hello,\nworld’
# 由此可见,在python中格式化字符%r,表示打印的是对象,什么都打印
w = “This is the left side of…”
e = “a string with a right side.”
print (w + e)
===========================================================
EX7
print (“Mary had a little lamb.”)
print (“Its fleece was white as {:s}.” .format(‘snow’))
print (“And everywhere that Mary went.”)
print (“.” * 10 ) #what’d that do?
end1 = “C”
end2 = “h”
end3 = “e”
end4 = “e”
end5 = “s”
end6 = “e”
end7 = “B”
end8 = “u”
end9 = “r”
end10 = “g”
end11 = “e”
end12 = “r”
# watch that comma at the end. try removing it to see what happens
print (end1 + end2 + end3 + end4 + end5 + end6, end=”)
print (end7 + end8 + end9 +end10 + end11 + end12)
=======================================================
EX8
formatter = “{!r} {!r} {!r} {!r}”
print (formatter .format(1, 2, 3, 4))
print (formatter .format(‘one’, ‘two’, ‘three’, ‘four’))
print (formatter .format(True, False, False, True))
print (formatter .format(formatter, formatter, formatter, formatter))
print (formatter .format(
“I had this thing.”,
“That you could type up right.” ,
“But it didn’t sing.”,
“So I said goodnight.”
))
# 第8行的打印结果是:’I had this thing.’ ‘That you could type up right.’ “But it didn’t sing.” ‘So I
# said goodnight.’
#注意【”But it didn’t sing.“】是用了双引号,原因是【didn’t】有了单引号。