|

Format Strings | Python tutorial in Sinhala #9 Video

Watch the video before reading this.

Let’s talk about format strings.

For an example ,

car = "toyota"

print(car) 

answer

toyota

Process finished with exit code 0

I take ‘ car ‘ as a variable.I substitute ‘ toyota’ for that. Then I print that variable. The final output is ‘toyota. That variable is replaced by a string.

We can add these strings. So that I ‘ll use ‘my’ as a variable for it.

car = "toyota"

my = "My favorite car brand is  + 
car" 

print (my) 

answer

My favorite car brand is 
toyota

Process finished with exit code 0

Here , I type ‘ My favorite car brand is + car for ‘my’ variable. Then I print second variable ‘my’. So the output is given here as ‘My favorite car brand is toyota’. You need to print the format in the variable. Here brackets represent the variable ‘car’.

Let’s take an another example ,

I’ll take 4 variables like this,

RAM = "8 GB"

HDD = "1 TB"

VGA = "2 GB" 

MySpec = My laptop has { }, RAM { },
 HDD { }, VGA { }

print(MySpec.format(RAM, HDD,
 VGA))

I run this coding. You can see the output is,

My laptop has 8 GB RAM, 
1 TB Hard Drive, 2 GB VGA

Process finished with exit code 0

Here, if we want to output this variable called ‘RAM’ in another place, you put these brackets and run this coding. You can see an error is shown as the output. We have replaced 3 variables. The brackets for those 3 variables are placed in this string. If we want to print ‘ RAM ‘ in another place. We have to type the order in these brackets. You know a number starts with ‘ 0 ‘ So that ‘ RAM ‘ is starting with ‘ 0 ‘ , ‘ HDD ‘ is starting with ‘ 1 ‘ and then ‘ VGA ‘ is starting with ‘2’. Format strings are in orders.

Now you need to type this order within those brackets.

RAM = "8 GB" 

HDD = "1 TB" 

VGA = "2 GB"

MySpec = "My laptop has {0}, 
RAM {1}, HDD {2}, 
VGA {0}

Here , last {0} is the value of the variable ‘RAM’.

My laptop has 8 GB RAM,
 1 TB Hard Drive, 2 GB VGA 
8 GB

Process finished with exit code 0

This shows ‘8 GB’ string substitutes for ‘RAM’ variable.

So we already discussed a lot about format strings.

Subscribe my channel for watch more educational contents.

Thank you.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *