3.4 Print concatenated strings
In Python, you can concatenate strings using several methods. Each method has its own use case, but for simple string concatenation, using the + operator or formatted string literals (f-strings) are typically the most straightforward and readable. In the next section we will also explain how to use print() with F-strings which is the preferred way to format strings in Python 3.6+.
Syntax:
Here's a summary of the basic syntax for using the + operator to concatenate strings.
# Basic concatenation
new_string = string1 + string2
# With additional characters
new_string = string1 + " " + string2
# Multiple strings
new_string = string1 + " " + string2 + " " + string3
Example 3.4.1 - Basic concatenation example to demonstrate the usage of + operator with strings.
Example 3.4.1 - Output
Now I know how to concatenate strings.
Example 3.4.2 - Concatenation example with variables.
Example 3.4.2 - Output
Hello World
Example 3.4.2 - Explanation
-
Here, two variables
str1andstr2are assigned the string values"Hello"and"World", respectively. -
The
+operator is used to concatenate (combine) the strings.- First,
str1 + " "is evaluated. This concatenates the string"Hello"with a single space character" ", resulting in the intermediate string"Hello ". - Then,
"Hello " + str2is evaluated. This concatenates the intermediate string"Hello "withstr2(which is"World"), resulting in the final string"Hello World".
- First,
-
The resulting concatenated string
"Hello World"is assigned to the variableresult. -
The
printfunction outputs the value of result to the console, which is"Hello World".
Example 3.4.3 - Concatenating multiple strings. You can concatenate multiple strings by chaining the + operator:
# Define multiple strings
string1 = "Hello"
string2 = "beautiful"
string3 = "World"
# Concatenate all strings with spaces in between
result = string1 + " " + string2 + " " + string3
# Print the result
print(result)
Example 3.4.3 - Output
Hello beautiful World
Example 3.4.3 - Explanation
This is very similar to Example 3.4.2 but we're just chaining the + operator to add more strings in one final string.
In summary, the + operator takes two strings and combines them into a new string. If you concatenate multiple strings, you can chain the + operator to add each part sequentially. This method is straightforward and readable for simple concatenation tasks.
Exercise 3.4.1 - Create a Python program that asks the user for their first name and their favorite color. Then, use the + operator to concatenate these two pieces of information into a sentence and print the sentence. The sentence should be in the format:
"[First name]'s favorite color is [color]."
Exercise 3.4.1 - Model Answer - Make sure to work out the exercise before checking the model answer.