Syllabus Lesson 4 of 239 · Python Foundations
Python Foundations

Working with Strings

A string is a sequence of characters, and each character has a position called an index. Indexing starts at 0:

word = "Python"
print(word[0])    # P
print(word[1])    # y

Negative indexes count from the end, so word[-1] is the last character (n).

Slicing

Grab a range with word[start:stop]. The start is included, the stop is not:

word = "Python"
print(word[0:3])  # Pyt
print(word[3:])   # hon  (to the end)

Handy tools

  • len(word) gives the length (6 here).
  • word.upper() and word.lower() change case.
  • text.strip() removes spaces from both ends.
  • + joins (concatenates) strings: "Py" + "thon".
messy = "   hello   "
clean = messy.strip()
print(clean.upper())   # HELLO
print(len(clean))      # 5
Your turn

Start with raw = " Floati ". Build a variable name that strips the spaces, then build shout as the upper-case version of name. Print shout (it should be FLOATI).

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output