the full guide

Strings: working with text

Slicing, joining, changing case, and the string methods you'll use every day.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

A string is a row of letters

Text in Python is called a string. Each letter has a position number, and counting starts at 0, not 1.

string_index.py
word = "PYTHON"

print(word[0])      # First letter
print(word[5])      # Last letter
print(word[-1])     # Also the last letter
print(len(word))    # How many letters

Output

P
N
N
6

Slicing: cutting out a piece

word[start:stop] gives the letters from start up to, but not including, stop.

string_slice.py
word = "PYTHON"

print(word[0:3])    # PYT
print(word[2:])     # From position 2 to the end
print(word[:2])     # From the start to position 2
print(word[::-1])   # Backwards

Output

PYT
THON
PY
NOHTYP

Useful string methods

string_methods.py
text = "  Machine Learning is fun  "

print(text.strip())                  # Remove spaces at the ends
print(text.upper())
print(text.lower())
print(text.replace("fun", "useful"))
print(text.strip().split(" "))       # Break into a list of words
print("Learning" in text)            # Is this inside?

Output

Machine Learning is fun
  MACHINE LEARNING IS FUN  
  machine learning is fun  
  Machine Learning is useful  
['Machine', 'Learning', 'is', 'fun']
True
MethodWhat it does
.strip()Removes spaces from both ends
.upper() / .lower()Changes the case
.replace(a, b)Swaps a for b
.split(x)Breaks text into a list at x
.count(x)Counts how many times x appears
.startswith(x)Checks how the text begins

Code challenge

Reverse the word “Namaste” and print it.

print("Namaste"[::-1])

Count how many times “a” appears in “banana”.

print("banana".count("a")) gives 3.

Finished reading?