Concatenation#
In most programming languages, concatenation involves adding or joining character strings.
For example, we could concatenate the strings Hello and world to create a Hello world message.
Examples#
In Python, we use the plus sign + to concatenate strings.
One option is to use concatenation as part of a print() statement:
# concatenation in a print statement
print("Hello " + "World!")
We can also use concatenation with string variables.
# concatenation with string variables
x = "Hello"
y = "World"
# concatenation with a print statement
print(x + y)
# conatenation with variable assignment
z = x + y
print(z)
We can compare string concatenation to how the addition operator (+) interacts with numeric values.
# numeric 'concatenation' in a print statement
print(5 + 7)
# numeric 'concatenation' with variable assignment
x = 5
y = 7
z = x + y
print(z)
NOTE: In Python, concatenation operations or the + operator will only work on variables or values of a common type.
# trying concatenation with an integer and string
year = 2023
school = "Notre Dame"
print(school + ", Class of " + year)
In the last section of this chapter, we’ll talk about how to convert data types to address this issue.
Comprehension Check#
![]() |
Concatenation Comprehension Check |
Application#
Q4: Write a program that creates first_name and last_name variables, and then uses concatenation to output a full_name variable. Answer to this question includes program + comments that document process and explain your code.
Q5: Create variables for each of the discrete pieces of information in “the standard Notre Dame introduction.”
Name
Class year
Home state/country
Major(s) / minor(s)
Residence hall
Use concatenation in combination with a print() statement to output a narrative introduction using the named variables.
Answer to this question includes program + comments that document process and explain your code.
Sample output for this program:
I'm Knute Rockne, class of 1914. I'm majoring in pharmacy and originally from Norway but grew up in Chicago. I live in Sorin Hall.
