Text processing · 1 / 14 Theory

Looping over and transforming characters

A string is a sequence of characters, and many text problems are solved by going through it character by character and building a new result. Remember that strings are immutable: they are never modified, a new string is always created.

Looping over a string

word = "Python"

for c in word:
    print(c, end=" ")   # P y t h o n
print()

for i, c in enumerate(word):
    print(i, c)         # 0 P, 1 y, 2 t ...

Building a new result

The usual pattern is to start with an empty string and add characters one by one:

text = "a1b2c3"

only_letters = ""
for c in text:
    if c.isalpha():
        only_letters += c

print(only_letters)  # abc

What kind of character it is

MethodReturns True if the character…Example
isalpha()is a letter"a".isalpha() → True
isdigit()is a digit"7".isdigit() → True
isalnum()is a letter or digit"_".isalnum() → False
isspace()is a space, tab or line break" ".isspace() → True
isupper()is a capital letter"A".isupper() → True
islower()is a lower-case letter"a".islower() → True

These methods also work with long strings, and then they check that all the characters meet the condition: "abc".isalpha() is True, but "ab1".isalpha() is False.

Character codes: ord and chr

Every character has an associated number, its Unicode code. ord converts a character into its number and chr does the opposite:

print(ord("a"))    # 97
print(ord("b"))    # 98
print(ord("A"))    # 65
print(chr(100))     # d
print(chr(ord("a") + 2))  # c

The letters from a to z have consecutive codes, and so do those from A to Z. That lets you do calculations with them:

c = "d"
position = ord(c) - ord("a")   # 3  (the position of d in the alphabet, starting at 0)
print(position)

print("a" <= c <= "z")      # True: comparing characters uses their codes

Example: shifting a letter

To move a letter forward some positions, going back to a after z, you use the remainder of the division by 26:

def shift(c, n):
    position = ord(c) - ord("a")
    new = (position + n) % 26
    return chr(new + ord("a"))

print(shift("a", 3))   # d
print(shift("y", 3))   # b  (after z, it goes back to a)
print(shift("d", -3))  # a  (also with negative shifts)

This is the basis of the Caesar cipher: the function is applied to each letter and the other characters are left as they are.

def caesar(text, n):
    result = ""
    for c in text:
        if "a" <= c <= "z":
            result += shift(c, n)
        else:
            result += c
    return result

print(caesar("hello world", 3))  # khoor zruog

Looping backwards and with slices

word = "python"

print(word[::-1])    # nohtyp  (reversed)
print(word[::2])     # pto     (one out of every two)
print(word[1:4])     # yth

Practice in Acronym, Count vowels and Caesar cipher.