String Format

(Read time is about 1 minutes)

So in this discussion we will have 2 topics:

These are at least 2 of the ways you can insert data into a string.

String Format

Given the following code

my_name = "Beanzilla"
print("Hello {0}!".format(my_name))

Hello Beanzilla!

So how does this work?

Well remember the box being like a variable?

We have a label on the box and then the content...

So... we are passing into the string "Hello {0}!" where the {0} gets replaced with our data from my_name to make "Hello Beanzilla!".

But what else can we do?

my_name = "Beanzilla"
my_fav_number = 9
print("I am {0} and my favorite number is {1}.".format(my_name, my_fav_number))

I am Beanzilla and my favorite number is 9.

This is a bit confusing...

Remember a computer always counts 0, 1, 2... (Unlike us 1, 2, 3...)

F String

No I am not cursing, f string as you will see has it's uses... but String Format can work where F String does not.

my_pets_name = "Fishstick"
print(f"Hello {my_pets_name}, have you been a good boy?")

Hello Fishstick, have you been a good boy?

Notice the difference between String Format and F String, One uses 0, 1, 2... the other uses the varible's name it's self.

Now, onto Loops