Text is handled in Python as a string, a sequence of characters. Strings appear in names, messages, files and web data, so knowing them well is essential.

Creating and Storing Strings

A string is created by enclosing characters in single quotes, double quotes, or triple quotes for text that spans several lines. Each character has a position called an index, which starts at 0 for the first character and at -1 for the last. A string is immutable, which means that its characters cannot be changed after it is created. Any change makes a new string. The function len() gives the number of characters.

Definition: String. An immutable sequence of characters enclosed in quotes.

String Operators

The operator + joins two strings and * repeats a string. The operator in checks whether a part occurs in a string, and the comparison operators compare strings by their character codes. Escape sequences such as \n for a new line and \t for a tab can be placed inside a string, and a raw string, written r"...", leaves the backslashes unchanged.

Built-in String Methods

Methods are called with a dot after the string. upper() and lower() change case, strip() removes spaces from the ends, and count(x) counts occurrences. find(x) gives the first index of x or -1, while index(x) raises an error if x is missing. replace(a, b) replaces every a with b. startswith() and endswith() test the ends. isdigit() and isalpha() test the kind of characters. Because strings are immutable, these methods return a new string and leave the original unchanged.

Because strings are sequences, they can also be used in a for loop, which visits one character at a time, and measured with len(). Two strings are equal only when every character matches, including the case, so "Python" and "python" are different. Methods such as lower() are often applied before comparing, so that the comparison ignores the case. The methods isalpha(), isdigit() and isalnum() are used to validate input, for example to check that a roll number contains only digits.

Table 1.5: Common string methods

Method Purpose Example result
upper() Capital letters "abc" gives "ABC"
find("b") First index or -1 "abc" gives 1
replace("a", "x") Replace text "banana" gives "bxnxnx"
count("a") Number of occurrences "banana" gives 3
strip() Remove end spaces " hi " gives "hi"

Example 1.5: Using string methods

Problem: For s = " Python Programming ", clean it and report its length, the number of letter m, and the first index of "Pro".

Solution:

  1. Apply strip() to remove the end spaces.
  2. Apply len(), count("m") and find("Pro") on the result.

Result: The cleaned string has 18 characters, contains 2 letters m, and "Pro" starts at index 7.

s = "  Python Programming  "
t = s.strip()
print(len(t), t.count("m"), t.find("Pro"), t.upper(), t.find("xyz"))
print("Py" in t, t.replace("Python", "Java"), t.startswith("Py"))

Output

18 2 7 PYTHON PROGRAMMING -1
True Java Programming True

Common mistakes

  • Trying to change one character with s[0] = "X", which raises a TypeError.
  • Expecting s.upper() to change s itself. It returns a new string.
  • Using index() when the text may be missing, which raises ValueError. Use find().

Key takeaways

  • Strings are immutable sequences of characters.
  • Indexing starts at 0, and -1 is the last character.
  • find() returns -1 if the text is missing.
  • String methods return new strings.

Practice questions

  1. Are strings mutable?
  2. What does find() return when the text is absent?
  3. What does "ab" * 3 give?

Answers to the practice questions

  1. No, they are immutable.
  2. -1.
  3. "ababab".

Sources

  • Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit I