4. Concatenate and repeat

Two operators work with strings.

+ concatenates: it joins two strings into a new one. Both operands must be strings.

* repeats: a string multiplied by an integer produces the string repeated that many times. The integer can be on either side.

+ does not convert numbers for you: "Age: " + 36 raises a TypeError. Cast the number with str() first.

Both operators return a new string. Strings are immutable, so neither operator changes the original value.

#01

Join strings with +

The + operator joins strings end to end. It needs a string on each side, so add a space as its own string between the words.

Print the result of joining "Hello", a space and "World" with +.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Join variables

The operands of + can be variables that hold strings.

Create two variables: first with the value "Ada" and last with the value "Lovelace". Print the full name, with a space between the two parts, using +.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Convert before joining

+ does not turn a number into text. Joining a string with an integer raises a TypeError.

Use str() to convert 36 to a string, then join it with "Age: ".

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Repeat a separator

* repeats a string. The right operand is an integer that says how many copies to make.

Print ten = characters using *.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Repeat a word

* works with any string, not only with single characters.

Print "ha" repeated three times.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

Combine both operators

* is evaluated before +, so "ab" * 2 is joined first and then the rest is concatenated.

Print the result of "ab" repeated twice, followed by "cd", using both operators.

Print exactly:

Create a free account to save your progress and unlock chapter 2.