Python Python String Manipulation and Formatting 1 — Questions and Answers
Question 1: Which method removes leading and trailing whitespace from a string?
- strip() (Correct answer)
- trim()
- clean()
- lstrip()
Correct answer: strip()
strip() removes whitespace (or specified characters) from both ends of a string.
Question 2: What does `'hello'.upper()` return?
- 'Hello'
- 'HELLO' (Correct answer)
- 'hello'
- None
Correct answer: 'HELLO'
upper() returns a new string with all characters converted to uppercase.
Question 3: What is the output of `'Python'.replace('P', 'J')`?
- 'python'
- 'Jython' (Correct answer)
- 'JPython'
- 'Python'
Correct answer: 'Jython'
replace() substitutes all occurrences of the first argument with the second, giving 'Jython'.
Question 4: What does `'a,b,c'.split(',')` return?
- 'a b c'
- ['a','b','c'] (Correct answer)
- ('a','b','c')
- {'a','b','c'}
Correct answer: ['a','b','c']
split() divides a string on the given separator and returns a list of substrings.
Question 5: Which f-string expression correctly formats a float to 2 decimal places?
- f'{value:.2}'
- f'{value:2f}'
- f'{value:.2f}' (Correct answer)
- f'{value|2f}'
Correct answer: f'{value:.2f}'
The format spec :.2f means fixed-point notation with 2 digits after the decimal.
Question 6: What does `'hello world'.title()` return?
- 'HELLO WORLD'
- 'hello world'
- 'Hello World' (Correct answer)
- 'Hello world'
Correct answer: 'Hello World'
title() capitalizes the first letter of every word and lowercases the rest.
Which method removes leading and trailing whitespace from a string?