Working with strings

Introduction

A string is a sequence of characters. You can pick out one character, take a slice, loop over every character, and use built-in methods that return new strings.

Most of the data a program touches is text: names, messages, addresses, search terms. Knowing how to pull text apart and tidy it up is one of the most practical skills in programming.

How it works

Indexing and slicing

word = "Dhaka"
print(word[0], word[-1])
print(word[1:4])
print(len(word))
Open in compiler

Positions start at 0: in "Dhaka", word[0] is 'D' and word[4] is 'a'. Negative positions count from the end, so word[-1] is the last character.

A slice word[1:4] takes positions 1, 2 and 3; it stops before 4, just like range. len(word) is the number of characters, 5.

ExpressionResult
word[0]'D'
word[-1]'a'
word[1:4]'hak'
word[:2]'Dh'
len(word)5

String methods

name = "  rahim uddin "
clean = name.strip().title()
print(clean)
print(clean.upper())
print(clean.replace("Uddin", "Ahmed"))
Open in compiler
  • strip() removes spaces at both ends; title() capitalises each word.
  • upper() and lower() change the case.
  • replace(old, new) swaps one piece of text for another.

Methods never change the original string, because strings cannot be changed. Each method returns a new string, so clean holds the result while name keeps its spaces.

Syntax

word[0]            # first character
word[-1]           # last character
word[1:4]          # positions 1, 2 and 3
word[::-1]         # reversed
word.strip().lower()
"a" in word

Example

text = "programming"
vowels = 0
for ch in text:
    if ch in "aeiou":
        vowels += 1
print(vowels)
Open in compiler

for ch in text: gives one character per round. ch in "aeiou" checks whether the character is a vowel. Step through and watch vowels reach 3 for the letters o, a and i.

Line by line

  1. text = "programming" is the string to examine.
  2. vowels = 0 starts the count.
  3. for ch in text: gives one character on each pass.
  4. ch in "aeiou" tests whether that character is a vowel.
  5. The count goes up only when the test passes.
  6. After the loop, print shows the total.

Expected result

3

In the real world

Sign-up forms trim and lower-case email addresses, so that Mitu@Example.com and mitu@example.com count as the same person. Search engines, spell checkers and chat filters all begin by going through text character by character.

Common mistakes

  • word[5] on a 5-letter word is an IndexError: the last position is 4.
  • word[0] = "d" is a TypeError. Build a new string instead: "d" + word[1:].
  • Calling a method without keeping its result: name.upper() alone changes nothing; write name = name.upper().

Best practices

  • Clean text as soon as you read it, with strip and a consistent case.
  • Keep the result of a method, because the original does not change.
  • Use in rather than writing your own search.

Summary

A string is a sequence of characters that you can index, slice and loop over. Strings cannot change, so methods such as upper, strip and replace return new strings.

Practice

Read a word and print it backwards using the slice word[::-1]. Then print YES if the word reads the same both ways, otherwise NO.

Quick check

1. With s = 'Python', what is s[1]?
2. What is 'Python'[0:2]?
3. After s = 'hi' and s.upper(), what is s?

Key takeaways

  • Positions start at 0, and negative positions count from the end.
  • A slice stops before its second number.
  • Strings cannot be changed, so methods return new ones.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.