Python Strings – 30 Questions and Answers
1. What is a string in Python? A sequence of Unicode characters enclosed in single ('...'), double ("...") or
triple quotes ('''...''' / """...""").
2. How do you create a string?
s = "Hello, World!"
3. How to access the first character of a string?
s = "Python"
print(s[0]) # Output: P
4. What does len() do with strings? Returns the number of characters:
len("Hello") # Output: 5
5. How do you get the last character of a string?
s = "Python"
print(s[-1]) # Output: n
6. What is string slicing? Extracting part of a string:
s = "Python"
print(s[1:4]) # Output: yth
7. How do you concatenate two strings?
a = "Hello"
b = "World"
c = a + " " + b # Output: "Hello World"
8. Are strings mutable in Python? No, strings are immutable. You cannot change characters in place.
9. What does str.upper() do? Returns the string in uppercase:
1
"hello".upper() # Output: "HELLO"
10. What does str.lower() do? Returns the string in lowercase:
"HELLO".lower() # Output: "hello"
11. How to remove whitespace from both ends of a string?
s = " Hello "
print(s.strip()) # Output: "Hello"
12. What does str.replace(old, new) do? Replaces all occurrences of old with new:
"banana".replace("a", "o") # Output: "bonono"
13. How to split a string into a list?
s = "a,b,c"
lst = s.split(",") # Output: ['a', 'b', 'c']
14. What does str.join() do? Joins elements of an iterable into a string:
".".join(['a', 'b', 'c']) # Output: "a.b.c"
15. How to check if a string starts with a prefix?
"Python".startswith("Py") # Output: True
16. How to check if a string ends with a suffix?
"Python".endswith("on") # Output: True
17. What does str.find() do? Returns the lowest index of the substring, or -1 if not found:
"banana".find("na") # Output: 2
18. What is str.count(sub)? Counts occurrences of sub:
2
"banana".count("a") # Output: 3
19. How to repeat a string multiple times?
"ha" * 3 # Output: "hahaha"
20. How to check if a string is numeric?
"123".isnumeric() # Output: True
21. How to check if all characters are alphabetic?
"abc".isalpha() # Output: True
22. What is str.title()? Capitalizes the first letter of each word:
"hello world".title() # Output: "Hello World"
23. What does str.capitalize() do? Capitalizes only the first character:
"hello".capitalize() # Output: "Hello"
24. How to escape characters in strings? Use \ (backslash):
"He said, \"Hi!\"" # Output: He said, "Hi!"
25. What are raw strings? Prefix with r to ignore escape sequences:
r"C:\new\folder" # Output: C:\new\folder
26. How to reverse a string?
s = "Python"
print(s[::-1]) # Output: "nohtyP"
27. What does str.zfill(width) do? Pads the string with zeros on the left:
3
"42".zfill(5) # Output: "00042"
28. How to center a string?
"hello".center(11, "*") # Output: "***hello***"
29. What is an f-string? Formatted string literal (Python 3.6+):
name = "Alice"
f"Hello, {name}!" # Output: "Hello, Alice!"
30. How to convert a number to a string?
str(123) # Output: "123"