Skip to content
Home » String Concatenation and Repetition in Python

String Concatenation and Repetition in Python

Spread the love

Today we’ll be talking about string concatenation and repetition. Concatenation and repetition work with all sequences, not only strings.

String Concatenation

string concatenation

If we put string literals next to each other (with or without spaces), they will be joined into one string. This is called concatenation:

>>> "Hello " "kids."
'Hello kids.'

>>> "Hello ""kids."
'Hello kids.'

This only works with string literals. If we try to concatenate string variables this way, we’ll get an error:

>>> greeting = "Hello "
>>> greeting "kids."
  File "<stdin>", line 1
    greeting "kids."
                   ^
SyntaxError: invalid syntax

We usually concatenate strings using the + sign. This is definitely necessary if we have string variables, but we usually also use the + sign for literals:

>>> "Hello" + " " + "kids!"    # literals
'Hello kids!'

>>> daughter = "Alice"         # variables
>>> son = "Josh"
>>> "I have a present for " + daughter + " and " + son + "."
'I have a present for Alice and Josh.'

String Repetition

string repetition

We use the multiplication operator * with strings to repeat them:

>>> "It's s" + "o" * 10 + " good!"
"It's soooooooooo good!"

>>> 'ha ' * 20
'ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha '

>>> question = "Were you shocked?"
>>> answer = question[10:12] + " "
>>> answer * 5
'ho ho ho ho ho '

We can also use the augmented assignment operator *=

So, a *= b is the same as a = a * b

>>> pattern1 = "-oo-"
>>> pattern1 = pattern1 * 3
>>> pattern1
'-oo--oo--oo-'

>>> pattern2 = "=XX="
>>> pattern2 *= 3
>>> pattern2
'=XX==XX==XX='

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of this article:


Spread the love
Tags:

Leave a Reply