Python String QA
Python String QA
1. What is a string in Python? A sequence of Unicode characters enclosed in single ('...'), double ("...") or
triple quotes ('''...''' / """...""").
s = "Hello, World!"
s = "Python"
print(s[0]) # Output: P
len("Hello") # Output: 5
s = "Python"
print(s[-1]) # Output: n
s = "Python"
print(s[1:4]) # Output: yth
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.
1
"hello".upper() # Output: "HELLO"
12. What does str.replace(old, new) do? Replaces all occurrences of old with new:
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:
17. What does str.find() do? Returns the lowest index of the substring, or -1 if not found:
"banana".find("na") # Output: 2
2
"banana".count("a") # Output: 3
23. What does str.capitalize() do? Capitalizes only the first character:
25. What are raw strings? Prefix with r to ignore escape sequences:
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"
name = "Alice"
f"Hello, {name}!" # Output: "Hello, Alice!"