Working with Text · practice
Combine and Repeat Text
Python can build a new
Join strings with +
With strings, the +
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:
When both values are strings, + joins text:
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 +:
An
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:
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
Build a name and divider
The starter code contains two name parts and a one-character separator.
Replace the two empty strings so:
full_namejoinsfirst_name, one space, andlast_name;dividerrepeatsseparatorten times.
The output must be:
Maya Chen
----------
Build both values from the existing
Task
Build full_name by joining the two name divider by repeating separator ten times.
Use * for the repetition. Keep the three starting
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.