In this guide, I’ll be talking about Concatenation and F-Strings, two ways you can add code together in Python.
Contents
Concatenation
Do you know what ‘Concatenation’ is? It’s like putting two words together in Python. We use the ‘+’ symbol to add a word to another word. It’s useful if we want to print something out neatly.
Example: Strings
For example, if we want to print out someone’s full name, we use Concatenation-
first_name = "johnny"
middle_name = "microwave"
last_name = "johnson"
full_name = "Hello, " + first_name + " " + middle_name + " " + last_name
print(full_name)
Concatenation happens on line 5. We just stick them together, and add spaces in between so it looks neater.
This is how it looks like-
Hello, johnny microwave johnson
Example: Integers
For integers, you can use Concatenation to do addition-
x = 3
y = 5
total = x + y
print(total)
8
Strings or Integers
However, all of them need to be either strings or integers. One common mistake people make is mixing them together, and getting an error in the end. For example-
name = "Emma"
age = 8
sentence = name + " is " + str(age) + " years old"
print(sentence)
We have a string: ‘Emma’ and a integer: 8. If we want to concatenate them, then we have to convert the integer into a string. (click here to know more)
At the end, it looks like this-
Emma is 8 years old
F-Strings
F-Strings can be used as a substitute for Concatenation. It lets you print stuff without converting an integer to a string!
To create an F-String, enter the letter ‘f’ before the statement you want to print. Then, you have to enter the variables you want to print in curly brackets, like this-
name = "Emma"
age = 8
print(f"{name} is {age} years old")
Results-
Emma is 8 years old
F-Strings are convenient and fast, so programmers tend to use it more.
Conclusion
That’s it for this guide! I hope it was helpful.
