In Python, text is stored as a String (str). To create one, wrap your text in quotes. You can use single (') or double (") quotes.

name = "Klein"
city = "Tingen"

If you have a large block of text (like a poem or a description) that spans multiple lines, use triple quotes:

description = """This is a long
text block that stays
formatted on new lines."""

Combining Strings

You can “glue” strings together with +, but you have to remember to add the spaces yourself:

first = "Klein"
last = "Moretti"
full = first + " " + last # "Klein Moretti"

The modern, cleaner way is using f-strings. Put an f before the quotes and use curly braces {} for your variables:

full = f"{first} {last}" # "Klein Moretti"

Indexes

Think of a string as a list of characters. Each character has a position (index), starting at 0.

word = "Python"

print(word[0])  # P
print(word[-1]) # n (The last character)

Slicing

You can grab a chunk of a string using [start:end].

The Rule: The start is included, but the end is excluded.

text = "Hello World"

print(text[0:5]) # "Hello" (Indexes 0, 1, 2, 3, 4)
print(text[:5])  # "Hello" (Same thing, empty start means "from the beginning")
print(text[6:])  # "World" (Empty end means "go to the very end")
print(text[:])   # "Hello World" (A complete copy of the string)

You can use negative numbers to slice relative to the end of the string. This is extremely useful when you don’t know how long the string is but you need the last few characters.

text = "Hello World"

# Start at index -5 (the 'W') and go to the end
print(text[-5:]) # "World"

# Get everything EXCEPT the last character
print(text[:-1]) # "Hello Worl"

The “Step” (and Reversing)

You can add a third number to your slice: [start:end:step]. The step tells Python how many characters to skip.

nums = "123456"
print(nums[::2]) # "135" (Every second character)

# Reverse a string
print(nums[::-1]) # "654321" (Step backward by 1)

Strings are Immutable

Immutable means “cannot be changed.” Once a string is created, you cannot swap out a single letter.

name = "Python"

# This will CRASH:
name[0] = "J" 
# TypeError: 'str' object does not support item assignment

If you want to change a string, you have to create a new one (for example, by using slicing).

Indexing vs. Slicing

  • If you try to access an index that doesn’t exist (e.g., "Hi"[10]), Python crashes with an IndexError.
  • If you try to slice a range that doesn’t exist (e.g., "Hi"[10:20]), Python does not crash. It just returns an empty string "".