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
only_digits with one parameter, text.text, in order.only_digits("+47 22-33-44") returns "47223344".
Run your code to see the output, then press Submit.
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"))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.