LESSON · 1 OF 6

Strings and quotes

Strings and quotes

A string is a piece of text. You write one by wrapping characters in quotes, and Python accepts single or double quotes with no difference in meaning:

python
name = 'web-01'
role = "database"

Pick whichever quote keeps you from having to escape. If the text itself contains a single quote, wrap it in double quotes, and the other way round:

python
message = "it's healthy"
path = 'the "prod" cluster'

Escaping and special characters

A backslash starts an escape sequence. The two you will meet most are \n for a newline and \t for a tab:

python
print("line one\nline two")

That prints across two lines. To put a literal backslash in a string, double it as \\.

Multi-line strings

Triple quotes, either ''' or """, let a string span several lines exactly as written:

python
banner = """
deploy-bot
version 1.0
"""

These are handy for blocks of text like a config template or a usage message.

Joining and repeating

The + operator joins strings end to end, and * repeats one:

python
full = "web" + "-" + "01"   # "web-01"
rule = "=" * 20              # twenty equals signs

Joining with + only works between strings. To join a string to a number you must convert the number first with str(), which the previous topic covered.

Length

The built-in len() function returns how many characters a string holds:

python
print(len("web-01"))   # 6

len() shows up constantly - checking whether input is empty, or whether a value is too long before you use it.

Spin up a fresh environment and practice live.
python-devops · fresh machine · ready in under a minute