How To Utilize Variables In Strings Python?

There are 5 🖐 super simple methods to use variables in strings (also called string formatting) in python.

Hello Pythonistas🙋‍♀️, welcome back. I hope you all are doing well.

In today’s post, we are going to take a look at how to use variables inside strings.

Let’s get started.

  • How To Utilize Variables In Strings Python?
  • String Concatenation
  • Print Function
  • Format Function
  • using % Operator
  • F-String

Previous post’s challenge’s solution

But, before we get started let’s first look👀 at the solution for the previous post’s challenge.

Solution Link: Click Here for the solution.

Output:-

I am python and I am 31 years old

Here, we simply used the print function to use the age variable in the given string.

There is a chance that you have used a different method, it can be anyone from the following methods. But, If your output is the same as mine then bingo🎉 you did it right.✅

Now, without wasting any further line(yes, line)📄 let’s get started.

What is the point of string formatting?

Imagine you are going to make a game🎮 like PUBG. To store a player’s points, coins🟡, stars⭐, diamonds💎, level, or whatever else it includes you would need to use variables.

Sounds fair? As these terms are constantly changing.🌀

Now suppose a player👦 wants to check no. of diamonds💎 he has for buying an outfit for his character. For this, you need to display output in the form of a string.

#-----GAME-----
diamonds = 10
#player won 
daimonds += 5
#player lost
diamonds -= 1
#player wants to see total no. of diamonds he has
print("The total no. of diamonds you have = ", diamonds)

Output:-

The total no. of diamonds you have = 14

But, if you were storing data in the form of variables all the way long, how would you display them in strings now? The answer is super simple using string formatting.

The one we did above is a way of string formatting.

Now I hope you got the point of using variables in strings.

Let’s see how can you solve your problem in multiple different ways.

String concatenation

Don’t be scared😰 by the fancy ✨word it just means using the '+' operator on strings. This example will make it clear:

game = "PUBG"
print(game+" is a game!!")

#!!Don't forget to give a space before 'is' otherwise
#PUBGis a game!!   #This will be your ouptut

Output:

PUBG is a game!!

Now, I won’t bore😪 you by saying that with this you can use a variable anywhere in the middle of the string and also at the end and that we can use more than one variable and more than one string.

I know you are smart😎 and curious🤩 enough to try it already.

This awesome✨ function provides you a facility to print variables, strings, and other data types inside of it by using a ',' comma as a separator. The example below will make it more clear.

show = "Monty Python's Flying Circus,"

print("Python is named after ", show, " a BBC comedy series from the 1970s.")

Output:-

Python is named after Monty Python's Flying Circus, a BBC comedy series from the 1970s.

Format function

It is a special✨ function for using variables in strings. The example below explains how to use it:-

action1 = "Sing"
action2 = "Dance"
action3 = "Be difficult"

print("Three things that python can't do:- {}, {}, and {}!!".format(action1, action2, action3))
#Keyword and position are also possible

Output:-

Three things that python can't do Sing, Dance, and Be difficult!!

You just need to put curly brackets {} wherever you want to insert a variable then after the string ends use the format function put the values and you are good👍 to go🚶‍♂️.

using % Operator

This method uses the modulus operator. Wherever in the string, you want to use a variable just put a % there and then write s, d, or f depending on the data type of data in the variable.

%s:- for string data type

%d:- for integer data type

%f:- for float data type

The example below will make it crystal💎 clear:-

name = "Python"
age = 31
number = 284.242

print("I am %s I am %d years old. I support floating point numbers like %f." % (name, age, number))

Output:-

I am Python I am 31 years old. I support floating point numbers like 284.242000 .

F-String

This is our final method it’s pretty easy compared to others while coding something big.

To use this you simply need to put a f at the beginning of the string and then, wherever you want to use a variable just use it inside curly brackets {variable}.

what ="f-string"
adjective = "fantastic"

print(f"{what} is {adjective}")

Output:-

f-string is fantastic

Which one is the best🏆 method for using variables in strings

The best of all is using f-strings as they look neat and also make the code more readable. Not only this it also make future changes in code easier and handier.

But, if you still doubt🤔 its usefulness then solve today’s challenge and figure out which seems to be the best method for you to use variables in strings.

If you want to read python’s official documentation for how to use variables in strings click here.

Conclusion

After reading this post check if you are able to clearly explain the following:-

  • What is string formatting?
  • Why string formatting?
  • All 5 methods of string formatting.
  • And, the best possible one to be used.

Challenge🧗‍♀️

Your challenge for this post is to use the given variables in the given story as and where specified. Where to use variables is defined by capital letter words and single quotations.

variables:-

  • son = “John”
  • father = “Dad”
  • thing = “car”
  • verb = “walked”

story:-

A teenage boy named ‘SON’ had just passed his driving test and asked his ‘FATHER’ if he could start using the family ‘THING’. The ‘FATHER’ said he’d make a deal with ‘SON’, “You bring your grades up from a C to a B average, study your Bible a little, and get your hair cut.

Then we’ll talk about the ‘THING'”. ‘SON’ thought about that for a moment, decided he’d settle for the offer and they agreed on it. After about six weeks, the ‘FATHER’ said, “‘SON’, you’ve brought your grades up and I’ve observed that you have been studying your Bible, but I’m disappointed you haven’t had your hair cut.”

‘SON’ said, “You know, ‘FATHER’, I’ve been thinking about that, and I’ve noticed in my studies of the Bible that Samson had long hair, ‘SON’ the Baptist had long hair, Moses had long hair, and there’s even strong evidence that Jesus had long hair.” His ‘FATHER’ replied, “Did you also notice that they all ‘VERB’ everywhere they went?”🤣

Go fast. I am waiting. Comment your answers below.

This was it for the post. Comment below suggestions if there and tell me whether you liked it or not. Do consider sharing this with your friends.

See you in the next post till then have a great time.😊 Bye bye👋