Python 3, an Illustrated Tour Transcripts
Chapter: Strings
Lecture: Walk-through: f-Strings
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
We're going to look at fstring test, open that up. The first part says assuming the variable stock and price exist
0:07
make a variable res that has Stock and then whatever the stock value is then price and whatever the price value is.
0:15
You should use an fstring to do this. So long behold here is stock and price. So let's make a variable called res, that's an fstring.
0:23
So to make an fstring we put an f in front of our string and I'm going to say Stock here and then I want the value of stock,
0:32
in this case I'll just put it in curly braces here and then price here with the value of price. We could do some formatting here.
0:44
In this case, it didn't particularly define that we include any specific formatting. Let's just run this and see if it works.
0:54
And it looks like it worked here. So this will give us a string that looks like that, pretty cool. The next part says assume the variable x exists.
1:03
And x is defined down here, create a variable answer that has the sin of x using math.sin to 2 decimal places.
1:11
And so it wants us to say x with the value of x then sin of x with the sin of that, use an f string to do that.
1:18
So the first thing we need to do is import the math libraries, we're going to say import math here.
1:25
Let's come down here and we'll make this variable called answer. It's going to be an fstring, so we'll put that in there.
1:32
We need x and we'll put the value of x there and we want sin of x with math.sin of x and we need to format it.
1:47
So in order to provide formatting, we put a colon at the end here and we're going to format this as a float.
1:54
So, I believe we need to say .2f to get 2 decimal places. Let's try that and see if it works.
2:09
Oh, I've got a typo here, I need to close off my embedding of my expression there. Let's try again. Okay, it looks like that worked.
2:23
So this shows you that not only can you put expressions in here, but you can put formatting with them as well using the formatting syntax.