Traversing Strings and String Methods

45 min read Working with Strings

This is a free course. Log in to run the code exercises and track your progress.

Traversing Strings and String Methods

A for loop can visit every character of a string in turn. This is called traversal. The membership operator in checks whether a character (or a smaller string) appears in a string.

text = "Digital India"
vowels = 0
for ch in text:
    if ch.lower() in "aeiou":
        vowels += 1
print(vowels)    # 6

Strings come with many methods. They return a new string or a value; the original string does not change.

  • upper(), lower(), title(): change the case.
  • count(sub): how many times sub occurs.
  • find(sub): index of the first occurrence, or -1.
  • replace(old, new): replace every occurrence.
  • isdigit(), isalpha(), isupper(), islower(): test the characters.
  • split(): break a sentence into a list of words.
Python exercise

Read a line of text and print three counts on three lines: Upper: , Lower: and Digits: (letters A-Z, letters a-z and digits 0-9).

text = input()
upper = lower = digits = 0
for ch in text:
    pass  # use isupper(), islower() and isdigit()
print("Upper:", upper)
print("Lower:", lower)
print("Digits:", digits)

Log in to edit and run this code.