I searched the site but it seems like this exercise from the book Learn Python the Hard way wasn’t covered in previous questions.
I have this exercise:
1)Find all the places where a string is put inside a string. There are four places.
2)Are you sure there’s only four places? How do you know? Maybe I like lying.
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not) #two strings inside a string, count is 2
print x
print y
print "I said: %r." % x #here, count is 3
print "I also said: '%s'." % y #here, count is 4
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
print w + e
I tried to solve it and commented the lines where I found a string inside a string(found4). But, the author’s second questions makes me worry I haven’t found all. Have I miss something? If yes, can you please tell me what?
If you interpret “putting a string inside a string” as “using a format character with a string argument”, you correctly identified all four occurrences. It may be more helpful to put away the useless instructions and explain what happens. For more information, have a look at the offical documentation for formatting characters. I’ll try to include some helpful exercises without trick questions.
%dis the formatting character for aSigned integer decimal(what most people think of when hearing a “number”). 10 is expressed in decimal and inserted into the string, resulting in the stringThere are 10 types of people..Excercise: What would
"7+6: %d" % (7+6)result in? Test it in your Python shell.Excercise: What would
"0x12: %d" % 0x12result in? Test it in your Python shell.Hint: A prefix of
0xmeans the following number is hexadecimal, i.e. base 16 instead of 10.%sinserts the string representation of a value. This example goes to show that if there is more than one%d,%sor so in a format string, we need to give that number of arguments, in a tuple or list. The difference between a tuple (round, braces) and a list [square, braces] is that a tuple is immutable(i.e. can’t be changed), but a list can.Excercise: Given the tuple
x = ('world', 'Hello'), construct a tupleywith the correct order of words. Dive Into Python’s introduction of tuples will help you understand the basics of tuples.%ris the representation of a value, ideally something you could enter into a Python shell. You can get the same representation with thereprfunction. For example,repr("a") == "'a'", whereasstr(a) == "a". For most types except string, the result ofreprandstr(or%rand%sin format strings) is the same.This concatenates two strings (i.e. puts one after the other). Note that the
+means something else (addition) if both arguments are numbers.Excercise: What is the result of
"3" + "4"? Test it in your Python shell.Excercise: Given
x = "3"; y = "4", print out the sum 7 (Hint).