Back to Course

Introduction to Python

0% Complete
0/0 Steps
  1. Python: Basics
    14Topics
    |
    15 Quizzes
  2. Python: Control Flow
    12Topics
    |
    12 Quizzes
  3. Python: Errors
    5Topics
    |
    5 Quizzes
Lesson 1, Topic 11
In Progress

Python: Concatenation

Yasin Cakal 4 Oct 2021
Lesson Progress
0% Complete

The + operator does not have to add two numbers; it can also be used to “add” two strings! String concatenation is the process of joining two strings. String concatenation creates a new string consisting of the contents of the first string followed by the contents of the second string without any added space in-between. Therefore, you have to remember to add the space if you’re concatenating two words. Here are some examples:

first_name = "Michael"
last_name = "Jordan"

# This is not what we want.
full_name = first_name + last_name
print(full_name) <meta charset="utf-8"># prints MichaelJordan

# Here is one way to fix it.
full_name = first_name + " " + last_name
print(full_name) # prints Michael Jordan

We create two variables to hold strings in this sample of code and then concatenate them. However, we noticed that the final result lacked a space between the two. Therefore, we added a space and reinitialized the full_name variable. We could have achieved the same result by adding the space after the first_name or before the last_name.

To concatenate a string with a number, you must first convert the number to a string using the str() function. If you’re trying to print() a numeric variable, rather than converting it to a string, you can use commas to pass it as a separate argument.

We can use str() to convert non-string variables to strings and then concatenate them. However, we do not need to convert a number to a string before passing it to a print statement as an argument. Let’s take a look at some more examples:

message_part = "Jordan wears the number"
space = " "
jersey_number = 23
message_full = message_part + space + str(jersey_number)

# Prints "Jordan wears the number 23"
print(message_full)

# Alternative method to print the same thing.
print(message_part, jersey_number)

Notice that the alternate method did not require the space variable to be added.

%d bloggers like this: