PCEP PCEP String Operations and Methods 2 — Questions and Answers
Question 1: What is the output of `len('Python 3')`?
- 8 (Correct answer)
- 7
- 6
- 9
Correct answer: 8
`len()` counts all characters including spaces, so 'Python 3' has 8 characters.
Question 2: Which method replaces all occurrences of a substring in a string?
- replace() (Correct answer)
- sub()
- swap()
- change()
Correct answer: replace()
`replace(old, new)` returns a new string with all occurrences of `old` replaced by `new`.
Question 3: What does `'Python'.find('th')` return?
- 2 (Correct answer)
- 3
- 1
- -1
Correct answer: 2
`find()` returns the index of the first occurrence of the substring; 'th' starts at index 2.
Question 4: What is the output of `'-'.join(['a', 'b', 'c'])`?
- a-b-c (Correct answer)
- a b c
- abc
- -a-b-c-
Correct answer: a-b-c
`join()` concatenates list elements with the calling string as a separator between each item.
Question 5: What does `'Hello World'.lower()` return?
- hello world (Correct answer)
- HELLO WORLD
- Hello World
- hELLO wORLD
Correct answer: hello world
`lower()` converts every character in the string to lowercase.
Question 6: Which escape sequence represents a newline character in a Python string?
- \n (Correct answer)
- \t
- \r
- \b
Correct answer: \n
`\n` is the escape sequence for a newline, which moves output to the next line.
What is the output of `len('Python 3')`?