0%

Working with Text · practice

Combine and Repeat Text

Python can build a new from existing strings. The original strings remain available, and the produces another .

Join strings with +

With strings, the + joins values in order:

Try it

The output is PythonLand. Python does not invent a space between the values.

Add the space explicitly when you need one:

name = first + " " + second

Joining strings this way is called concatenation. The name is less important than the idea: + creates one string by placing the values next to each other.

+ depends on the value types

You have already used + to add numbers:

Try it

When both values are strings, + joins text:

Try it

In the first example, we get the integer 7. In the second, the result is the string "43".

Python does not directly join a string and an integer with +:

Try it

An is often clearer when you combine several values into a message:

people = 3
destination = "the museum"
message = f"Number of people: {people}. Destination: {destination}."
print(message)

Repeat a string with *

Multiplying a string by an integer repeats it:

Try it

The output is eight hyphens:

--------

This is useful for small text patterns and experiments. It should not replace site styling or proper layout tools.

What will this program print?

word = "go"
print(word + "!" * 3)

Watch new strings being built

The exercise editor’s Step view shows the three starting strings in the Locals panel before full_name and divider appear. Each new value exists as soon as its runs. The final two instructions display values that the program has already built.

Build a name and divider

The starter code contains two name parts and a one-character separator.

Replace the two empty strings so:

  • full_name joins first_name, one space, and last_name;

  • divider repeats separator ten times.

The output must be:

Maya Chen
----------

Build both values from the existing . Do not type the complete name or ten hyphens as finished answers.

Task

Build full_name by joining the two name with one space. Build divider by repeating separator ten times.

Use * for the repetition. Keep the three starting unchanged.

Produce:

Maya Chen
----------

Use Step in the exercise editor. Before the print instructions run, check that Locals already contains Maya Chen and ----------; then continue and watch their output appear.