Working with Strings in Python

In this post I explain quotes, escaping, concatenation, and repetition for Python strings.
TopicsPython

Working with Strings in Python

In Python you can create strings with either single quotes or double quotes.

'hello'  # single-quoted string
"hello"  # double-quoted string

From Python's point of view these are the same string. We can check that with the == operator:

'hello' == "hello"  # True

Single and Double Quotes

Different quote styles are useful when you want to nest quotes inside a string. For example:

'I said: "hello"'

Or the other way around, with single quotes inside double quotes:

"I said: 'hello'"

These two strings are different because a single quote character and a double quote character are not the same thing.

"I said: 'hello'" == 'I said: "hello"'  # False

Escaping Quotes

If you need double quotes inside a string that is itself wrapped in double quotes, you need to escape them with a backslash \:

"I said: \"hello\""

Without escaping, Python raises a syntax error because it can no longer tell where the string starts and ends.

String Concatenation

You can add strings together. This is called concatenation. The result is a new string made from both parts.

'Hello' + ' Vadya'  # 'Hello Vadya'

You can also place string literals next to each other without a plus sign. Python joins them automatically:

'Hello' " Vadya"  # 'Hello Vadya'

String Repetition

You can multiply a string by an integer. Python repeats the string that many times:

"Hello " * 3  # 'Hello Hello Hello '

If you multiply by zero or a negative integer, the result is an empty string:

"Hello " * 0       # ''
"Hello " * (-100)  # ''