πŸŽ“ Velnov

🐍 Python · Topic 4 of 20

Strings β€” Python Questions with Answers

Start with the study notes on Strings (definitions, examples and a quick revision), then work through 30 practice questions, each with the correct answer and a clear explanation of why it is right. When you are ready, take this topic as an interactive quiz to test yourself.

14 easy Β· 13 medium Β· 3 hard Β· Part of Python: Master Python from basics to advanced - 20 topics.

Topic overview

Strings – working with text

1. What is a string?

A string (str) is a sequence of characters, written in single, double or triple quotes. Strings are immutable: once created, they cannot be changed.

a = 'hello'
b = "hello"
menu = """1. Start
2. Quit"""
print(a == b)
print(menu)
OutputTrue
1. Start
2. Quit

2. Indexing

Each character has a position (index) starting at 0. Negative indexes count from the end.

s = "python"
print(s[0], s[2])
print(s[-1], s[-2])
print(len(s))
Outputp t
n o
6

3. Slicing

s[start:end:step] takes a piece of the string, up to but not including end.

s = "python"
print(s[1:4])
print(s[:3], s[3:])
print(s[::2])
print(s[::-1])      # reversed
Outputyth
pyt hon
pto
nohtyp

Example: Palindrome check: s == s[::-1] is True for "madam".

4. Common string methods

Methods return a new string; the original is unchanged.

s = "  Hello World  "
print(s.strip())
print(s.strip().lower(), s.strip().upper())
print("hello world".title())
print("banana".replace("a", "o"))
print("banana".count("a"))
print("report.pdf".endswith(".pdf"))
print("123".isdigit(), "12.5".isdigit())
OutputHello World
hello world HELLO WORLD
Hello World
bonono
3
True
True False

5. split() and join()

print("a,b,c".split(","))
print("one two  three".split())
words = ["a", "b", "c"]
print("-".join(words))
Output['a', 'b', 'c']
['one', 'two', 'three']
a-b-c

6. Searching: in, find() and index()

s = "hello"
print("ll" in s)
print(s.find("ll"), s.find("xy"))
OutputTrue
2 -1

7. f-strings and format()

An f-string starts with f and fills in {expressions} inside the text. A format code after : controls the display, e.g. .2f for 2 decimal places.

name, age = "Ana", 21
print(f"Hello {name}, you are {age}")
print(f"Next year: {age + 1}")
price = 100
print(f"Total: {price * 1.18:.2f}")
print("Hello {}, you are {}".format(name, age))
OutputHello Ana, you are 21
Next year: 22
Total: 118.00
Hello Ana, you are 21

8. Joining, repeating and immutability

print("ab" * 3)
print("-" * 10)
s = "hello"
s = "H" + s[1:]     # build a new string
print(s)
age = 21
print("Age: " + str(age))
Outputababab
----------
Hello
Age: 21

Remember: s[0] = "H" is a TypeError, because strings can't be changed in place. And "Age: " + 21 is also a TypeError: convert with str(), or use an f-string.

9. Characters and comparison

Strings compare alphabetically by character codes. ord() gives a character's number, and chr() does the reverse.

print("apple" < "banana")
print("Zoo" < "apple")      # capitals come first
print(ord("A"), chr(66))
OutputTrue
True
65 B

10. Common misconceptions

MisconceptionCorrect understanding
s[1:4] includes index 4.The end index is excluded: s[1:4] gives indexes 1, 2 and 3.
s.upper() changes s.Strings are immutable; upper() returns a new string.
"Age: " + 21 works.You cannot add str and int; use str(21) or an f-string.
find() raises an error when not found.find() returns -1; index() is the one that raises ValueError.
\n is two characters.\n is one character (a new line); len("a\nb") is 3.

11. Quick revision

Index
Position of a character, starting at 0.
Negative index
Counts from the end; -1 is the last character.
Slice
s[start:end:step]; end is excluded.
s[::-1]
The string reversed.
split()
Cuts a string into a list.
join()
Glues a list of strings together.
f-string
f"...{expr}..." fills in values.
Immutable
Cannot be changed after it is created.

12. Test your understanding

  1. For s = "python", what is s[-1]?

    Show answer

    "n"

  2. What does "python"[1:4] give?

    Show answer

    "yth"

  3. How do you reverse a string s?

    Show answer

    s[::-1]

  4. What does "a,b,c".split(",") return?

    Show answer

    ['a', 'b', 'c']

  5. What does "-".join(["a", "b"]) return?

    Show answer

    "a-b"

  6. What does "hello".find("z") return?

    Show answer

    -1

  7. How do you show a price with 2 decimal places in an f-string?

    Show answer

    f"{price:.2f}"

  8. Why does s[0] = "H" fail?

    Show answer

    Strings are immutable; build a new string instead.

Key takeaway: Strings are immutable sequences: index from 0, slice with [start:end:step], and use methods, split/join and f-strings to build new text.

Notes written by Velnov. Every code example with an output was run in Python 3 to check that the output shown is exactly what Python prints.

Key concepts in this topic

IndexingZero-based countingNegative indexingSlicingHalf-open rangesDefaultsStepPalindromesString methodslower()upper()casefold()lstrip()rstrip()Cleaning inputjoin()Listssplit()find()index()in operatorMembership testingf-stringsformat()

Jump to: Easy Β· Medium Β· Hard

Easy questions (14)

Q1. easy

What is the output of: s = "python" print(s[0])

s = "python"
#     012345   <- index positions
print(s[0])   # p
print(s[2])   # t
  1. A p
  2. B y
  3. C python
  4. D Error

Answer: A β€” p

String indexing starts at 0: s[0] is the FIRST character 'p', s[1] is 'y', and so on.

IndexingZero-based counting

Q2. easy

What is the output of: s = "python" print(s[-1])

s = "python"
print(s[-1])   # n (last)
print(s[-2])   # o (second last)
  1. A p
  2. B n
  3. C o
  4. D Error

Answer: B β€” n

Negative indexes count from the END: s[-1] is the last character 'n', s[-2] is 'o'. Very handy for grabbing the end without knowing the length.

Negative indexing

Q4. easy

What is the output of: print("python"[:3])

s = "python"
print(s[:3])   # pyt
print(s[3:])   # hon
print(s[:])    # python (full copy)
  1. A pyt
  2. B pyth
  3. C hon
  4. D Error

Answer: A β€” pyt

Leaving out the start means 'from the beginning': [:3] takes indexes 0, 1, 2 -> 'pyt'. Similarly [3:] means 'from index 3 to the end' -> 'hon'.

SlicingDefaults

Q7. easy

What is the output of: print("hello".upper())

s = "hello"
print(s.upper())   # HELLO
print(s)            # hello - original untouched
  1. A Hello
  2. B HELLO
  3. C hello
  4. D hELLO

Answer: B β€” HELLO

.upper() returns a NEW string with all letters uppercase. The original string is unchanged (strings can't be modified).

String methodslower()

Q8. easy

Which method converts "PyThOn" to "python"?

a = input("yes/no: ")
if a.lower() == "yes":   # accepts YES, Yes, yes...
    print("ok")
  1. A small()
  2. B lowercase()
  3. C lower()
  4. D downcase()

Answer: C β€” lower()

.lower() returns the string with every letter in lowercase - commonly used to compare text case-insensitively.

upper()casefold()

Q9. easy

What does " hello ".strip() return?

s = "  hello  "
print(s.strip())    # 'hello'
print(s.lstrip())   # 'hello  '
print(s.rstrip())   # '  hello'
  1. A "hello"
  2. B " hello"
  3. C "hello "
  4. D "h e l l o"

Answer: A β€” "hello"

.strip() removes whitespace (spaces, tabs, newlines) from BOTH ends of a string - the middle is untouched. lstrip() and rstrip() do only the left or right side.

  • Always strip() user input - people love typing stray spaces.

lstrip()rstrip()Cleaning input

Q10. easy

What does "a,b,c".split(",") return?

print("a,b,c".split(","))    # ['a', 'b', 'c']
print("one two  three".split()) # ['one', 'two', 'three']
  1. A "abc"
  2. B ['a', 'b', 'c']
  3. C ('a', 'b', 'c')
  4. D 'a' 'b' 'c'

Answer: B β€” ['a', 'b', 'c']

.split(separator) cuts a string into a LIST of pieces. "a,b,c".split(",") gives ['a', 'b', 'c']. With no argument, split() cuts on any whitespace.

join()Lists

Q12. easy

What does "banana".replace("a", "o") return?

print("banana".replace("a", "o"))     # bonono
print("banana".replace("a", "o", 1))  # bonana
  1. A bonono
  2. B bonana
  3. C banana
  4. D bonan

Answer: A β€” bonono

.replace(old, new) replaces EVERY occurrence by default: all three a's become o's -> 'bonono'. A third argument limits the count: replace("a", "o", 1) -> 'bonana'.

String methods

Q14. easy

What is the output of: print("py" in "python")

print("py" in "python")      # True
print("java" in "python")    # False
print("x" not in "python")   # True
  1. A True
  2. B False
  3. C 0
  4. D Error

Answer: A β€” True

The in operator checks whether a substring exists inside a string: "py" appears at the start of "python", so True. It's the cleanest way to test 'contains'.

in operatorMembership testing

Q15. easy

name = "Ana" Which line prints: Hello Ana! using an f-string?

name = "Ana"
print(f"Hello {name}!")   # Hello Ana!
print("Hello {name}!")    # Hello {name}!  (no f!)
  1. A print(f"Hello {name}!")
  2. B print("Hello {name}!")
  3. C print(f"Hello name!")
  4. D print("Hello" + {name})

Answer: A β€” print(f"Hello {name}!")

An f-string starts with f before the quote and fills in {expressions}: f"Hello {name}!" -> Hello Ana!. Option B lacks the f, so it prints the braces literally.

  • f-strings (Python 3.6+) are the modern, preferred way to format text.

f-stringsformat()

Q18. easy

What is the output of: print("ab" * 3)

print("ab" * 3)    # ababab
print("-" * 20)    # --------------------
  1. A ababab
  2. B ab3
  3. C ab ab ab
  4. D Error

Answer: A β€” ababab

Multiplying a string by an integer repeats it: "ab" * 3 -> "ababab". Handy for separators: print("-" * 30).

String repetitionOperators

Q19. easy

What does "banana".count("an") return?

print("banana".count("an"))   # 2
print("banana".count("a"))    # 3
  1. A 1
  2. B 2
  3. C 3
  4. D 0

Answer: B β€” 2

.count(sub) counts non-overlapping occurrences: 'banana' contains 'an' at positions 1 and 3 -> 2.

String methods

Q21. easy

What is the output of: print("hello world".title())

s = "hello world"
print(s.title())        # Hello World
print(s.capitalize())   # Hello world
  1. A Hello world
  2. B HELLO WORLD
  3. C Hello World
  4. D hello World

Answer: C β€” Hello World

.title() capitalizes the first letter of EVERY word. .capitalize() would capitalize only the first letter of the whole string ('Hello world').

capitalize()String methods

Q25. easy

How do you create a string that spans several lines?

menu = """1. Start
2. Options
3. Quit"""
print(menu)
  1. A Triple quotes: """line1\nline2""" style blocks
  2. B Using the multiline keyword
  3. C Ending each line with a comma
  4. D It's not possible

Answer: A β€” Triple quotes: """line1\nline2""" style blocks

Triple-quoted strings keep their line breaks exactly as typed - ideal for long messages, menus, or SQL queries.

Triple quotesDocstrings

Medium questions (13)

Q3. medium

What is the output of: s = "python" print(s[1:4])

s = "python"
print(s[1:4])   # yth (indexes 1,2,3)
print(s[0:2])   # py
  1. A yth
  2. B ytho
  3. C pyt
  4. D tho

Answer: A β€” yth

Slicing s[start:end] takes characters from index start UP TO BUT NOT INCLUDING end: indexes 1, 2, 3 -> 'yth'. The end index is always excluded.

  • Remember: the slice grabs (end - start) characters.

SlicingHalf-open ranges

Q5. medium

What is the output of: print("abcdef"[::2])

print("abcdef"[::2])    # ace
print("abcdef"[1::2])   # bdf
  1. A abc
  2. B ace
  3. C bdf
  4. D fedcba

Answer: B β€” ace

The third slice number is the STEP: [::2] takes every 2nd character starting from index 0 -> a, c, e.

SlicingStep

Q6. medium

What is the classic one-liner to REVERSE a string s?

s = "python"
print(s[::-1])   # nohtyp
  1. A s.reverse()
  2. B reverse(s)
  3. C s[::-1]
  4. D s[-1:1]

Answer: C β€” s[::-1]

A step of -1 walks the string backwards: s[::-1] returns the reversed string. Strings have no .reverse() method (lists do).

  • Famous interview question: check palindrome with s == s[::-1].

SlicingPalindromes

Q11. medium

What is the output of: print("-".join(["a", "b", "c"]))

words = ["a", "b", "c"]
print("-".join(words))   # a-b-c
print("".join(words))    # abc
print(", ".join(words))  # a, b, c
  1. A abc
  2. B a-b-c
  3. C -abc-
  4. D ['a-b-c']

Answer: B β€” a-b-c

.join() is the opposite of split(): it glues a list of strings together using the string it's called on as the separator: "-".join(...) -> a-b-c.

  • The separator comes FIRST - a common point of confusion.

split()Lists

Q13. medium

What is the difference between find() and index() on strings?

s = "hello"
print(s.find("ll"))    # 2
print(s.find("xy"))    # -1
# s.index("xy")         # ValueError!
  1. A No difference
  2. B find() returns -1 when not found; index() raises ValueError
  3. C index() returns -1; find() raises an error
  4. D find() only works on numbers

Answer: B β€” find() returns -1 when not found; index() raises ValueError

Both return the position of a substring. When the substring is absent, find() politely returns -1 while index() raises ValueError. Use find() when absence is normal.

find()index()in operator

Q16. medium

What is the output of: print(f"{2 + 3}")

price = 100
print(f"Total: {price * 1.18:.2f}")  # Total: 118.00
  1. A 2 + 3
  2. B 5
  3. C {2 + 3}
  4. D Error

Answer: B β€” 5

f-string braces can hold ANY expression, not just variable names - it's evaluated and the result inserted: f"{2 + 3}" -> "5".

  • After a colon you can add formatting, e.g. :.2f = 2 decimal places.

f-stringsFormat specifiers

Q17. medium

What happens with: s = "hello" s[0] = "H"

s = "hello"
# s[0] = "H"          # TypeError!
s = "H" + s[1:]       # build a new string
print(s)               # Hello
  1. A s becomes "Hello"
  2. B TypeError - strings are immutable
  3. C s becomes "H"
  4. D Nothing

Answer: B β€” TypeError - strings are immutable

Strings CANNOT be changed in place - assigning to a character raises TypeError. To 'change' a string you build a new one: "H" + s[1:].

  • Immutability is why all string methods RETURN a new string.

ImmutabilitySlicing

Q20. medium

Which expression checks if a filename ends with ".pdf"?

f = "report.pdf"
print(f.endswith(".pdf"))       # True
print(f.startswith("rep"))      # True
  1. A filename.endswith(".pdf")
  2. B filename.end(".pdf")
  3. C filename[-4] == ".pdf"
  4. D filename.last(".pdf")

Answer: A β€” filename.endswith(".pdf")

.endswith() and .startswith() test the ends of a string and return True/False. Option C is close but wrong - filename[-4] is a single character; you'd need filename[-4:].

startswith()Slicing

Q22. medium

What does "123".isdigit() return?

print("123".isdigit())    # True
print("12.5".isdigit())   # False
print("abc".isdigit())    # False
  1. A True
  2. B False
  3. C 123
  4. D Error

Answer: A β€” True

.isdigit() is True when every character is a digit 0-9. Great for validating input BEFORE calling int(). "12.5".isdigit() is False (the dot isn't a digit).

isalpha()Input validation

Q23. medium

What is the output of: print("apple" < "banana")

print("apple" < "banana")   # True
print("Zoo" < "apple")      # True! capitals come before lowercase
  1. A True
  2. B False
  3. C Error
  4. D 5

Answer: A β€” True

Strings compare alphabetically (by character codes), letter by letter: 'a' < 'b', so "apple" < "banana" is True. This is why sorting a list of strings gives alphabetical order.

  • All UPPERCASE letters sort before all lowercase in default comparisons.

Orderingsorted()ord()

Q26. medium

What is the output of: age = 21 print("Age: " + age)

age = 21
print("Age: " + str(age))   # works
print(f"Age: {age}")         # best
print("Age:", age)           # also works
  1. A Age: 21
  2. B TypeError - can't concatenate str and int
  3. C Age: "21"
  4. D Age:21

Answer: B β€” TypeError - can't concatenate str and int

+ can't join a string with a number. Fix it with str(age), an f-string, or a comma in print (which handles any type).

TypeErrorf-stringsstr()

Q27. medium

What is the output of: print("Hello {}, you are {}".format("Ana", 21))

print("Hello {}, you are {}".format("Ana", 21))
# same as:
name, age = "Ana", 21
print(f"Hello {name}, you are {age}")
  1. A Hello Ana, you are 21
  2. B Hello {}, you are {}
  3. C Hello 21, you are Ana
  4. D Error

Answer: A β€” Hello Ana, you are 21

.format() fills the {} placeholders in order: first {} gets "Ana", second gets 21. f-strings do the same job more readably, but .format() is common in older code.

format()f-strings

Q29. medium

Which expression removes only the TRAILING newline from s = "data\n"?

line = "data\n"
print(repr(line.rstrip()))   # 'data'
  1. A s.rstrip()
  2. B s.strip("data")
  3. C s.replace("n", "")
  4. D s.cut()

Answer: A β€” s.rstrip()

.rstrip() strips whitespace (including \n) from the right end only - the standard way to clean lines read from a file. Option C would delete the letter n from 'data' too!

strip()Reading files

Hard questions (3)

Q24. hard

What do ord("A") and chr(66) return?

print(ord("A"))   # 65
print(chr(66))     # B
print(chr(ord("a") + 1))  # b
  1. A 65 and "B"
  2. B "A" and 66
  3. C 1 and "66"
  4. D Error for both

Answer: A β€” 65 and "B"

ord() gives a character's Unicode number (A = 65) and chr() does the reverse (66 = B). They're inverses: chr(ord("A")) is "A" again.

  • Used in Caesar ciphers and character math puzzles.

UnicodeASCII

Q28. hard

What is the output of: print(len("a\nb"))

print(len("a\nb"))    # 3
print(len("\t"))       # 1
print(len("\\"))       # 1 (one backslash)
  1. A 4
  2. B 3
  3. C 2
  4. D 5

Answer: B β€” 3

\n is ONE character (the newline), not two. So the string contains 'a', newline, 'b' - length 3.

Escape sequenceslen()

Q30. hard

s = "madam" - which expression checks if s is a palindrome?

s = "madam"
print(s == s[::-1])   # True

s = "python"
print(s == s[::-1])   # False
  1. A s == s[::-1]
  2. B s.palindrome()
  3. C s == reverse(s)
  4. D s[::-1] == True

Answer: A β€” s == s[::-1]

A palindrome reads the same backwards. s[::-1] is the reversed string, so comparing it to the original does the check in one line. There's no built-in palindrome() or reverse() function for strings.

SlicingInterview questions

Practice β€œStrings” as a quiz