๐Ÿ“ฑ Code Python on your phone with Python Coding - Learn PythonGet the free Android app โ†’
  1. Home
  2. Python exercises
  3. String exercises

Python exercises ยท 6 tasks

Python string exercises

Six exercises that cover what you'll do with text every day in Python: slicing, string methods, counting characters and building new strings.

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.

0 / 6 solved

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.

    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.

      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.

        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.

          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.

            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.

              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 โ†’

              Practise on your phone too

              Python Coding - Learn Python for Android: a real Python 3 interpreter, code editor, 26 example programs and 12 marked exercises.

              Get it on Google Play

              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.

              Keep practising

              Updated 2026-10-22 ยท every solution is tested on Python 3