Looping Over Strings

Looping Over Strings

A for loop visits each character of a string in order, and the accumulator pattern builds new strings the same way it builds numbers and lists — start with "", add characters with +=:

def double_letters(word):
    result = ""
    for letter in word:
        result += letter + letter
    return result

print(double_letters("hey"))

Output:

hheeyy

Two character methods are useful inside such loops. isdigit is True for a digit character; isalpha is True for a letter:

print("7".isdigit())
print("x".isdigit())
print("x".isalpha())

Output:

True
False
True

Exercise

  1. Define a function named only_digits with one parameter, text.
  2. It returns a string containing only the digit characters of text, in order.

only_digits("+47 22-33-44") returns "47223344".

Run your code to see the output, then press Submit.

Tests

import unittest


class TestOnlyDigits(unittest.TestCase):
    def test_phone_number(self):
        self.assertEqual(only_digits("+47 22-33-44"), "47223344")

    def test_no_digits_gives_empty_string(self):
        self.assertEqual(only_digits("abc"), "")

    def test_all_digits_are_kept(self):
        self.assertEqual(only_digits("123"), "123")

    def test_empty_string(self):
        self.assertEqual(only_digits(""), "")
def only_digits(text):
    result = ""
    for character in text:
        if character.isdigit():
            result += character
    return result


print(only_digits("+47 22-33-44"))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.