Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 9

String Concatenation and Repetition

Recommended resources

Hello! In our last lesson, we explored how Python handles numbers using arithmetic operators. We saw how symbols like + and * perform addition and multiplication on integers and floats. Now, we'll turn our attention to the str data type and see how these same operators take on a new role when working with text.

This lesson will teach you how to perform basic string operations. You will learn to combine strings to form longer sentences—a process called concatenation—and how to repeat a string multiple times. These are fundamental skills for creating dynamic and readable output in your programs, from crafting personalized greetings to formatting text.

Joining Strings: Concatenation

In programming, the act of joining strings end-to-end is called concatenation. Python uses the same + operator that we used for addition, but when applied to strings, it links them together.

For example, if you have two string variables, first_name = "Jane" and last_name = "Doe", you can combine them to create a full name. This process creates a new string containing the content of both original strings.

The following video provides a concise introduction to string concatenation.

String Concatenation | Python Tutorial

This video, "String Concatenation | Python Tutorial" from Portfolio Courses, clearly defines and demonstrates how to join strings.

Watch from the beginning to see how the + operator works. Pay close attention to how spaces are handled. Definition: Understand what concatenation means. Basic Example: See how two strings are joined. Adding Spaces: Note how to explicitly add a space between strings, a very common task.

As you saw in the video, Python doesn't automatically add spaces between concatenated strings. You must include them yourself as a string literal, like this: ' '.

This example demonstrates how to concatenate two string variables, `str1` and `str2`. Notice the space included in the `'Hello '` string to ensure the words in the final output are separated.

For a detailed textual explanation, the following resource provides another look at this concept.

Manipulating Strings in Python

This article from Programming Historian offers clear, well-written explanations of string manipulation.

Find the section titled "String Operators", and read the subsection on Concatenate. It reinforces the idea that you must explicitly add spaces.

A Common Pitfall: Mixing Strings and Numbers

A frequent error for beginners is trying to concatenate a string with a number. Your code will stop with a TypeError because Python doesn't know whether you intend to do math or join text.




# This will cause an error!
age = 25
message = "I am " + age + " years old." 



# TypeError: can only concatenate str (not "int") to str

To fix this, you must explicitly convert the number into a string using the str() function before concatenation. This function takes a number (or another data type) as input and returns its string representation.




# This works correctly!
age = 25
message = "I am " + str(age) + " years old."
print(message)



# Output: I am 25 years old.

The video from Portfolio Courses also covers this exact issue and its solution.

String Concatenation | Python Tutorial

This segment explains the common TypeError and demonstrates the correct way to combine strings and numbers.

Watch the section from the error demonstration to see how str() is used to resolve the problem.


Repeating Strings: Repetition

Just as the + operator has a special meaning for strings, so does the * operator. Instead of multiplication, it performs repetition, creating a new string by repeating an original string a specified number of times. This is very useful for creating separators or patterns in your output.

For instance, '-' * 10 will produce a new string '----------'.

The Neso Academy video below provides a thorough explanation of the string repetition operator.

String Operators in Python (Part 1)

In "String Operators in Python (Part 1)," the presenter details how the string repetition operator works.

Watch the segment from the introduction to string repetition. The presenter explains the basic syntax (n * s) and shows what happens when you "multiply" a string.

Now, let's revisit the Programming Historian article to read about the multiplication operator in the context of strings.

Manipulating Strings in Python

This article provides another clear example of string repetition.

In the same section as before, "String Operators", now read the subsection titled Multiply.


Practice Exercise: Create a Welcome Banner

It's time to put these two operations into practice. Open your code editor and create a new Python file. Your task is to write a script that generates a personalized welcome banner.

  1. Create a variable named user_name and assign it a name as a string (e.g., "Maria").
  2. Create a banner_line variable by repeating the = character 30 times using the repetition operator.
  3. Create a welcome_message variable by concatenating the strings "Welcome, ", the user_name variable, and "!".
  4. Write print() statements to display the banner in the following format:
    • The banner_line.
    • The welcome_message.
    • The banner_line again.

Your final output should look something like this:

==============================
Welcome, Maria!
==============================

This exercise combines both concatenation and repetition to create a formatted, dynamic piece of text.


Conclusion

In this lesson, you've learned how to manipulate strings in two fundamental ways, moving beyond just storing static text. You now have the tools to build and format strings dynamically within your code.

Here are the main takeaways:

  • The concatenation operator (+) joins two or more strings together to create a new one.
  • The repetition operator (*) repeats a string a given number of times.
  • You cannot directly concatenate a string with a number; you must first convert the number to a string using the str() function.
  • These operations are essential for constructing messages, formatting output, and working with textual data.

We've had a glimpse of type casting with str(). In our next lesson, we will dive deeper into this topic, exploring how to convert data between different types like int, float, and str to make your programs more flexible and robust.