Recall that in lesson 2 of Python Black Hat you learned to add outputs together. Using the + operator. You can do the same with this but remember to add a space where you need to. See the example below:
sentence1 = “My name is”
name = “Emily”
longsentence = sentence1 + ‘ ‘ + name
print(longsentence)
Output:
My name is Emily
However, you have to be careful when adding different variables together. You can’t add a number to a string. The example below will send back an error message.
age = 21 #this is an int
sentence2 = “My age is” #this is a string
print(age + sentences) #you can not add an int and string like this
Output: Error
So how can we combine strings and numbers?
We can use the built-in function called format(). The format() takes the passed argument and formats them and places them into the string where the place holders, {}, are. See the example below.
age = 21 #this is an int
sentence2 = “My age is {}” .format(age)
print(sentence2)
Output: My age is 21
This tool becomes very useful in complex programs when taking user inputs and displaying them. You can add multiple place holders in a sentence, you just have to format them in the right order. See the example below.
age = 21 #this is an int
name = “Emily”
sentence2 = “Hi my name is {} and I am {} years old” .format(name, age)
print(sentence2)
Output:
Hi my name is Emily and I am 21 years old