String Formating¶
-
Assume you have a variable
x
that refers to an integer. Write code to print out the value of x surrounded by arrows. E.g., if the value of x is 7, you should print this:-->7<--
1x = 7
2# replace this comment with your code
3
(strform1)
Use%d
as the specifier in the format string.21print('-->%d<--' % x)
2
(strform1_a)
-
Given two integers
v1
andv2
, use string formatting to create a stringvalues
showing the values ofv1
andv2
with a ‘, ‘ between (a comma and a space).21# replace this comment with your code
2
(strform2)
Make sure you put your values in a tuple.21values = '%d, %d' % (v1, v2)
2
(strform2_a)
-
If
v1
= 1,v2
= 3.75, andv3
= “hi”, create a string in variableresStr
with valuehi! 1 != 3.75 :-(
.21# replace this comment with your code
2
(strform3)
Put your three values in a tuple in the orderv3
,v1
,v2
. To make sure you have only 2 digits after the decimal, use this format specifier:%.2f
21resStr = '%s! %d != %.2f :-(' % (v3, v1, v2)
2
(strform3_a)
-
If
v1
= 1, andv2
= 2, create a string in variableresStr
which refers tovariable 1 is 1 (1.0) and variable 2 is 2 (2.0)
.21# replace this comment with your code
2
(strform4)
To make sure you have only 1 digit after the decimal, use this format specifier:
%.1f
You can use a variable multiple times in the same tuple.
21resStr = 'variable 1 is %d (%.1f) and variable 2 is %d (%.1f)' % (v1, v1, v2, v2)
2
(strform4_a)