How to use strings in Python

In this article, let’s see how strings are used in Python.

I. What is a string?

In Python, strings are sequences of characters. Strings can be any length and can include any character such as letters, numbers, symbols, and whitespace (spaces, tabs, new lines).

A string is created by entering text between two single or double quotation marks.

>>> "Hello World"
'Hello World'

II. Asign string to variable

To assign string to variable, add an equal sign and the string after variable name:

name = 'Hanna'

To assign a multiline string to a variable, we can use three quotes:

greeting = """Teacher: Good morning.
Students: Good morning, teacher"""

III. Common string mistakes

  • Don’t forget to use quotes. Without quotes, you’ll get a name error.
>>> name = Anna
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Anna' is not defined
  • Use the same time of quotation mark. If you start with a double quote, end with a double quote.
name = "Anna"

IV. Escape Characters

Backslashes are used to escape characters in a Python string.

For example, to print a string with quotation marks:

txt = "She said \"Hello\"."
# She said "Hello"

Other special characters:

  • \n begins a new line.
  • \' single quote
  • \\ backlash
  • \t pushes the content behind it 1 tab.
  • \b removes the space in front of it.
  • \xnn In addition, you can also use to print other special characters using the \xnn syntax, where n is 0->9, or a->f or A->F.

V. String operations

1. String Concatenation

To concatenate two strings, we can use the + operator.

a = "Hello"
b = "World"
c = a + " " + b

We can also use print(f'string {variable}').

For example

>>> a = 'World'
>>> print(f'Hello {a}')
Hello World

2. Multiply string

Strings can be multiplied by integers. This produces a repeated version of the original string.

>>> print("Hello"*3)

VI. Check a string

In Python, you can check if a string contains a substring by using the keyword in or not in.

>>> "H" in "Student"
>>> "I" in "I love Python"

VII. Indexing a string

We can select specific letters from this string using the index: stringName[index]

In there:

  • stringName is the name of the variable containing the string, or string.
  • index is the position of the character you want to retrieve.
    • The first character of a string start at index 0.
    • The end character starts from -1.

For example

>>> name = "strawberry"
>>> name[1]

If you try to select a non-integer index, we would get a TypeError.

>>> name = "strawberry"
>>> name[2.5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

Negative indices

Negative indices count backward from the end of the string.

For example, string_name[-1] is the last character of the string, string_name[-2] is the second last character of the string, etc.

VIII. Strings are Immutable

Strings are immutable, so we cannot change a string once it is created.

>>> name = "strawberry"
>>> name[0] = "B"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

VIII. Slicing a string

We can select substring with the following syntax:


When we slice a string, we create a new string that starts at the first_index and ends at (but excludes) the last_index.

For example

>>> name = "strawberry"
>>> name[2:5]

We can also have open-ended selections.

  • If we remove the first_index, the slice starts at the beginning of the string
  • If we remove the last_index, the slice continues to the end of the string.
>>> name = "strawberry"
>>> name[:5]
>>> name[5:]

IX. Check length

We can use len() function to determine the length of a string.

length = len("Hello")
# Output: 5

As indices start at 0, the final character in a string has the index of len(string_name) - 1.

Example 1

>>> name = "strawberry"
>>> length = len(name) - 1
>>> name[length]

Example 2: To find the last three letters of a string:

last_three_letters = string_name[len(string_name)-3:]

X. String methods

Python has several string methods that we can use.

  • upper()
  • lower()
  • find()
  • replace()

You can read more methods with string methods article.