In: Computer Science
1) answer parts a through d using pythons new f string formating. All parts have examples of what is expected to be returned
a) Write a function with prototype “def fstring1(a,b,c,d,e):” whose body simply returns a single f-string such that print(fstring1(13,12,11,10,9)) followed by print(fstring1(666,666,666,666,666)) generates exactly
val1= 13, val2=0012, val3= b, val4=0x000A, val5=9. Done!
val1= 666, val2=0666, val3= 29a, val4=0x029A, val5=666. Done!
Pay close attention to the number of spaces, leading zeros, capitalization when in hexidecimal, etc
b) Write a function with prototype “def fstring2(a,b,c,d,e):” whose body simply returns a single f-string such that print(fstring2(13,12,11,10,9)) followed by print(fstring2(666,666,666,666,666)) generates exactly
val1= 13.0, val2=0012.0, val3= 1.1e+01, val4=001.0e+01 val5=9.0E+00. Done!
val1= 666.0, val2=0666.0, val3= 6.7e+02, val4=006.7e+02 val5=6.7E+02. Done!
Pay close attention to the number of spaces, leading zeros, capitalization (of “E”), etc.
c) Write a function with prototype “def fstring3(a,b,c,d):” whose body simply returns a single f-string such that print(fstring3("Ho","Ho", "Ho", "way to go!")) followed by print(fstring3("Eeny", "meeny", "miny", "moe")) generates exactly
val1=Ho , val2= Ho , val3= Ho, val4=way to go!. Done!
val1=Eeny , val2= meeny , val3= miny, val4=moe. Done!
Pay close attention to the field widths and justification
d) Write test code for the above functions that tests using the given strings.
Solution: Required code for the 4 parts have been given below along with the output. Comments have been placed to depict the part.
#part a
def fstring1(a,b,c,d,e):
return(f"val1={a}, val2={b:04}, val3={c:x},val4=0x{d:04X},val5={e}. Done!" )
#part b
def fstring2(a,b,c,d,e):
return(f"val1={a:.1f}, val2={b:06.1f}, val3={c:.1e},val4={d:09.1e},val5={e:.1E}. Done!" )
#part c
def fstring3(a,b,c,d):
x = len(a) + 1
y = len(b) + 2
z = len(c) + 1
return(f"val1={a:<{x}}, val2={b:^{y}}, val3={c:>{z}}, val4={d}. Done!")
#part d
if __name__ == "__main__":
print(fstring1(13,12,11,10,9))
print(fstring1(666,666,666,666,666))
print(fstring2(13,12,11,10,9))
print(fstring2(666,666,666,666,666))
print(fstring3("Ho","Ho", "Ho", "way to go!"))
print(fstring3("Eeny", "meeny", "miny", "moe"))
output
val1=13, val2=0012,
val3=b,val4=0x000A,val5=9. Done!
val1=666, val2=0666, val3=29a,val4=0x029A,val5=666.
Done!
val1=13.0, val2=0012.0,
val3=1.1e+01,val4=001.0e+01,val5=9.0E+00. Done!
val1=666.0, val2=0666.0, val3=6.7e+02,val4=006.7e+02,val5=6.7E+02.
Done!
val1=Ho , val2= Ho , val3= Ho,
val4=way to go!. Done!
val1=Eeny , val2= meeny , val3= miny, val4=moe. Done!