Quick answerThese Python string exercises practise slicing (s[::-1]), methods such as upper(), split() and join(), counting characters and checking palindromes. Write the code in the browser, press Check, and see each test pass or fail.
String tools you'll need
s[0] is the first character and s[-1] the last; s[1:4] is a slice; s[::-1] is the string reversed. Useful methods: lower(), upper(), title(), strip(), split(), " ".join(words), replace(old, new) and count(x). Strings are immutable โ methods return a new string.
Exercises
1. Reverse a stringeasy
Read a line of text and print it backwards.
๐ก A slice with step โ1 walks backwards: text[::-1]
Show solution
text = input()
print(text[::-1])
[start:stop:step] with an empty start and stop and a step of โ1 covers the whole string from the end.
2. Count the vowelseasy
Read a line and print how many vowels (a, e, i, o, u โ upper or lower case) it contains.
๐ก Loop over text.lower() and check if ch in "aeiou".
Show solution
text = input()
count = 0
for ch in text.lower():
if ch in "aeiou":
count += 1
print(count)
Lower-casing first means one check covers both cases. A one-liner: sum(ch in "aeiou" for ch in text.lower()).
3. Palindrome checkermedium
Read a phrase and print True if it reads the same backwards, ignoring case and spaces, otherwise False. Never odd or even โ True.
๐ก Clean it first: s = phrase.replace(" ", "").lower(), then compare s == s[::-1].
Show solution
phrase = input()
s = phrase.replace(" ", "").lower()
print(s == s[::-1])
Printing a comparison prints the boolean itself, so no if is needed.
4. Initialseasy
Read a full name and print its initials in capitals, each followed by a dot. ada lovelace โ A.L.
๐ก name.split() gives the words; take word[0].upper() + "." for each.
Show solution
name = input()
print("".join(word[0].upper() + "." for word in name.split()))
split() with no argument splits on any run of spaces, and "".join(...) glues the pieces together.
5. Longest wordmedium
Read a sentence and print its longest word. If two words tie, print the first one.
๐ก max(words, key=len) returns the first longest item.
Show solution
sentence = input()
print(max(sentence.split(), key=len))
key=len tells max to compare lengths. When lengths tie, max keeps the first one it saw.
6. Run-length encodinghard
Compress repeated letters: aaabccdddd โ a3b1c2d4. Read the string and print the encoding.
๐ก Walk through the string keeping the current letter and a counter; when the letter changes, add letter + str(count) to the result.
Show solution
s = input()
result = ""
count = 1
for i in range(1, len(s) + 1):
if i < len(s) and s[i] == s[i - 1]:
count += 1
else:
result += s[i - 1] + str(count)
count = 1
print(result)
Looping one past the end (len(s) + 1) lets the last group be written by the same else branch. itertools.groupby is a neat alternative.
Next topic: List exercises โ
Python Coding - Learn Python for Android: a real Python 3 interpreter, code editor, 26 example programs and 12 marked exercises.
Frequently asked questions
How do I reverse a string in Python?
Use slicing with a negative step: text[::-1].
Why can't I change a character with s[0] = 'X'?
Strings are immutable. Build a new string instead, e.g. s = "X" + s[1:].
What's the difference between split() and split(' ')?
split() splits on any whitespace and ignores repeats; split(' ') splits on every single space, so double spaces give empty strings.