Skip to content

Strings

In Python the type used to represent text is called string. You can use strings to provide feedback to the user during program execution or output logs from the program.

You can generate strings from other strings:

>>> firstname = "Ada"
>>> lastname = "Lovelace"
>>> fullname = firstname + " " + lastname
>>> print(fullname)
Ada Lovelace

You can convert most types to strings:

>>> age = str(25)
>>> print("You are " + age + " years old")
You are 25 years old

Without the str(25) conversion, the print() statement would have produced a TypeError.

Other ways to concatenate (join) strings:

>>> 'Hello' ' world'
'Hello world'
>>> ('Hello'
... ' world')
'Hello world'

Use pairs of triple single or double quotes for multi-line strings:

>>> html = """
<body>
    <h1>About</h1>
</body>
"""

Suppressing newline character in multi-line strings

When printed, the html variable will output a newline character at both ends of the string.

This is often not what you want. Use a \ to suppress a newline character anywhere in the string.

>>> html = """\
... <body>
...     <h1>About</h1>
... </body>"""

The special \ character is used to escape special characters such as quotes, non-printable characters and other characters that have meaning in the language (such as parentheses, braces, brackets, ...).

>>> "\"Watch out!\" she cried"
'"Watch out!" she cried'

Raw strings

There are times when you need to output the literal \. You can handle this in two ways:

  • escape the \: path="C:\\Program files\\Python314"
  • use raw strings: path=r"C:\Program files\Python314"

Uppercase and lowercase:

>>> 'python'.upper()
'PYTHON'
>>> 'PYTHON'.lower()
'python'

Get part of a string:

>>> lang = 'python'
>>> lang[0].upper + lang[1:]
'Python'
>>> lang[:-1] + lang[-1].upper()
'pythoN'

Indexing and slicing

lang[0] in the previous example is called indexing. This means retrieving the character at the given position in the string. Strings are sequences and their indexes start from 0.

The expression var[n:m] is called slicing. This means retrieving a substring starting at position n (inclusive) up to position m (exclusive).

Negative index values are permitted and they start at the end of the string.