Strings & string methods

Computer Science · Python

Question 1 of 10

0

    What does this Python code print? s = "cherry" print(len(s))

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Strings & string methods explained

    A string is a sequence of characters written inside quotes, and Python provides methods that work on strings. Strings are immutable, which means a method such as upper() never changes the original string. Instead it returns a new string, so you must store the result if you want to keep it.

    Each character has an index, starting at 0. Negative indexes count from the end, so -1 is the last character. A slice s[start:stop] returns the characters from start up to, but not including, stop. The len() function returns the number of characters.

    Common methods include lower() and upper() for case, strip() to remove spaces at each end, replace(old, new), and find(text), which returns the index of the first match or -1 if there is none. split(",") turns a string into a list of pieces, and "-".join(items) does the reverse. Strings can also be built with f-strings such as f"Hello {name}".

    word = "  Python  "
    clean = word.strip().lower()
    print(clean[0:3], len(clean), clean.find("th"))
    

    Worked example

    Trace the program above.

    1. word.strip() removes the spaces at both ends, leaving "Python".
    2. .lower() returns a new string "python", which is stored in clean.
    3. clean[0:3] takes the characters at indexes 0, 1 and 2: "pyt".
    4. len(clean) counts the six characters: 6.
    5. clean.find("th") finds "th" starting at index 2, because p is 0, y is 1, t is 2 and h is 3.

    The output is pyt 6 2.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Python code print? s = "kiwi" print(len(s))

    • Medium

      What does this Python code print? s = "mango-cherry" print(s.find("x"))

    • Hard

      What does this Python code print? s = "kiwi-lemon-orange" parts = s.split("-") print(len(parts[1]))