message = "Hello, Super Cat!"
print(message)
Run this code in the console. What do you see? Now it's your turn. Following the above example, think of any message. Right it down as a string. Save it in a variable and display the variable value using the print function. What you've got?
We can combine strings. There is a method for that, called – concatenation. All we have to do to concatenate strings is to put addition operator + between them. Easy right? If so, let's get concatenating!
"Super Cat" + "saves the day!"
Now, let's display the two concatenated strings:
print("Super Cat" + "saves the day!")
Write this code into the console and hit run. Have you noticed something weird? Hmm. It looks like our lines stuck together. No worries. We can quickly fix that. There are several ways to do it but let's stick with the most simple – leave a space between the quote and string:
print("Super Cat" +" saves the day!")
Have you fixed that? Hit run again.
5 Strings Concatenation And Variables
Note that we can concatenate a string only with another string. Or a string-formatted value. For example, if we created a variable and assigned a string-formatted value to it, we can also concatenate such a variable with another string. In the example below, I created a variable (hero) and assigned a string-formatted value (Super Cat) to it. Then I displayed this value in concatenation with another string (VS Duper Dog).
hero = "Super Cat"
print(hero + " VS Duper Dog")
Try this code out. What message do you get? Now, change the code as you like. You can even concatenate more than two strings! Alter and run the code. See how the output changes!
Now let's talk about what string formatting is. We have already learned how to concatenate strings using the + operator. The + operator can only concatenate a string with another string. But what if we want to concatenate a string with something that doesn't have a string format? In this case, we use string formatting to turn a value that doesn't have a string format into a string-formatted value. To do so, we need two things:
The format() method to format the non-string value and insert it inside the string's placeholder.
The placeholder itself – {} for the non-string value.