Python Python String Manipulation and Formatting 2 — Questions and Answers
Question 1: How do you check if a string starts with a specific prefix in Python?
- str.prefix('py')
- str.startswith('py') (Correct answer)
- str.begins('py')
- str[:2] == 'py' only
Correct answer: str.startswith('py')
startswith() returns True if the string begins with the specified prefix.
Question 2: What is the result of `''.join(['a','b','c'])`?
- 'a b c'
- ['a','b','c']
- 'abc' (Correct answer)
- ('a','b','c')
Correct answer: 'abc'
join() concatenates list elements using the calling string as separator; an empty string means no separator.
Question 3: What does `'Python'[1:4]` evaluate to?
- 'Pyt'
- 'yth' (Correct answer)
- 'ytho'
- 'thon'
Correct answer: 'yth'
Slicing [1:4] returns characters at indices 1, 2, and 3, which are 'y', 't', 'h' → 'yth'.
Question 4: Which method returns the index of the first occurrence of a substring, or -1 if not found?
- index()
- find() (Correct answer)
- search()
- locate()
Correct answer: find()
find() returns the lowest index where the substring is found, or -1 if absent; index() raises ValueError instead.
Question 5: What does the format string `'{0} {1}'.format('Hello', 'World')` produce?
- 'Hello'
- 'World'
- 'Hello World' (Correct answer)
- '0 1'
Correct answer: 'Hello World'
Positional placeholders {0} and {1} are replaced with the first and second format arguments.
Question 6: What is the output of `len('hello world')`?
- 10
- 11 (Correct answer)
- 9
- 12
Correct answer: 11
The string 'hello world' has 5 + 1 space + 5 = 11 characters.
How do you check if a string starts with a specific prefix in Python?