Skip to content
Laviyx Learn

Try

Python Strings Practice

Practise indexing and slicing strings, string methods like split, join, strip and replace, and formatting output with f-strings.

Beginner8 problemsUpdated

Review first: Strings

  1. 1.Initials from a full name

    Beginner

    Given full_name = "asha devi rao", print the initials in capitals with dots, like A.D.R.

    Show hint

    split() gives a list of words. Take word[0] from each and use upper().

    Show solution
    Python
    full_name = "asha devi rao"
    
    initials = "".join(word[0].upper() + "." for word in full_name.split())
    
    print(initials)
    Output
    A.D.R.
  2. 2.Count the vowels

    Beginner

    Count how many vowels (a, e, i, o, u, in either case) are in text = "Python Is Easy To Learn".

    Show hint

    Loop over text.lower() and check if ch in "aeiou".

    Show solution
    Python
    text = "Python Is Easy To Learn"
    
    count = 0
    for ch in text.lower():
        if ch in "aeiou":
            count += 1
    
    print(count)
    Output
    7

    A shorter version is sum(1 for ch in text.lower() if ch in "aeiou").

  3. 3.Is it a palindrome?

    Beginner

    A palindrome reads the same backwards. Ignoring case and spaces, print whether each of "Racecar", "Never odd or even" and "Python" is a palindrome.

    Show hint

    Clean the string with .lower() and .replace(" ", ""), then compare it with its reverse, s[::-1].

    Show solution
    Python
    def is_palindrome(text):
        cleaned = text.lower().replace(" ", "")
        return cleaned == cleaned[::-1]
    
    
    for phrase in ["Racecar", "Never odd or even", "Python"]:
        print(phrase, "->", is_palindrome(phrase))
    Output
    Racecar -> True
    Never odd or even -> True
    Python -> False
  4. 4.Clean up messy text

    Beginner

    Clean raw = " hello WORLD, welcome to PYTHON " so it prints as Hello World, Welcome To Python, with single spaces and no spaces at the ends.

    Show hint

    split() with no argument splits on any run of spaces and drops the empty pieces. Then " ".join() and .title().

    Show solution
    Python
    raw = "   hello WORLD,   welcome to   PYTHON   "
    
    cleaned = " ".join(raw.split()).title()
    
    print(cleaned)
    Output
    Hello World, Welcome To Python
  5. 5.Reverse the word order

    Beginner

    Reverse the order of the words in sentence = "practice makes progress", giving progress makes practice.

    Show hint

    Split into a list of words, reverse the list, and join it back together.

    Show solution
    Python
    sentence = "practice makes progress"
    
    words = sentence.split()
    reversed_sentence = " ".join(reversed(words))
    
    print(reversed_sentence)
    Output
    progress makes practice
  6. 6.Hide part of an email

    Beginner

    Given email = "asha.rao@example.com", keep the first letter and the domain, and replace the rest of the name with *, giving a*******@example.com.

    Show hint

    email.split("@") separates the name from the domain. "*" * n repeats a character n times.

    Show solution
    Python
    email = "asha.rao@example.com"
    
    name, domain = email.split("@")
    masked = name[0] + "*" * (len(name) - 1) + "@" + domain
    
    print(masked)
    Output
    a*******@example.com
  7. 7.Print an aligned receipt

    Beginner

    Print these items as an aligned receipt: names left-aligned in 10 characters, prices right-aligned in 8 characters with 2 decimals, and a total line.

    items = [("Tea", 30), ("Sandwich", 85.5), ("Cake", 120)]

    Show hint

    In an f-string, {name:<10} left-aligns in 10 characters and {price:>8.2f} right-aligns a number with 2 decimals.

    Show solution
    Python
    items = [("Tea", 30), ("Sandwich", 85.5), ("Cake", 120)]
    
    total = 0
    for name, price in items:
        print(f"{name:<10}{price:>8.2f}")
        total += price
    
    print("-" * 18)
    print(f"{'Total':<10}{total:>8.2f}")
    Output
    Tea          30.00
    Sandwich     85.50
    Cake        120.00
    ------------------
    Total       235.50
  8. 8.Find and count

    Beginner

    In text = "the cat sat on the mat with the hat", print how many times "the" appears, the position of the first "at", and whether the text starts with "the".

    Show hint

    count(), find() and startswith() are string methods.

    Show solution
    Python
    text = "the cat sat on the mat with the hat"
    
    print(text.count("the"))
    print(text.find("at"))
    print(text.startswith("the"))
    Output
    3
    5
    True

    find() returns -1 when the text is not found, while index() raises a ValueError. Use find() when "not found" is a normal case.