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'

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"""

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"

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"

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)

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"

Indexing a string

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

The first character of a string start at index 0.

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.

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

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:]


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:]

String Methods

1. lower()

.lower() method returns the string in lower case:

a = "Hello World"
# Output: hello world

2. upper()

.upper() method returns the string in upper case:

a = "Hello World"

3. title()

.title() returns the string in title case, which means the first letter of each word is capitalized.

a = "hello world"
# Output: Hello World

4. split()

.split() splits a string into a list of items:

  • If no argument is passed, the default behavior is to split on whitespace.
  • If an argument is passed to the method, that value is used as the delimiter on which to split the string.

Example 1

a = "Hello World"
# Output: ['Hello', 'World']

Example 2

students = "Jane,Anna,John,Peter"
# Output: ['Jane', 'Anna', 'John', 'Peter']

We can also split strings using escape sequences.

  • \n Newline allows us to split a multi-line string by line breaks
  • \t Horizontal Tab allows us to split a string by tabs
long_string = \
This is a long paragraph
To split this
We use escape sequences"""

lst = long_string.split('\n')

# Output: ['Hello', 'This is a long paragraph', 'To split this', 'We use escape sequences']

5. join()

.join() joins a list of strings together with a given delimiter.



For example

lst = ["The", "weather", "is", "sunny"]
print(" ".join(lst))
# Output: The weather is sunny

6. strip()

.strip() removes characters from the beginning and end of a string.

We can specify a set of characters to be stripped with a string argument. With no arguments to the method, whitespace is removed.

a = "    Hello World   "

7. replace()

.replace() method replaces a string with another string.


string_name.replace(character_being_replaced, new_character)

For example

a = "Hello World"
print(a.replace("H", "J"))
# Output: Jello World

8. find()

.find() searches the string for a specific value and returns the first index value where that value is located.

a = "Hello World"
# Output: 6

9. format()

.format() formats specified values in a string.


string.format(value1, value2...)

For example

def favorite_food(topping, food):
  return "My favorite food is {} {}.".format(topping, food)

print(favorite_food("vanilla", "ice-cream"))
# Output: My favorite food is vanilla ice-cream.