Which method is used to format strings in Python?
A
replace() B
format() C
join() D
style()
Analysis & Theory
`format()` is used to insert values into placeholders in a string.
What is the output of `'Hello, {}!'.format('Alice')`?
A
Hello, {}! B
Hello, ! C
Hello, Alice! D
Hello Alice
Analysis & Theory
`format()` replaces `{}` with the value 'Alice'.
What will `'{} + {} = {}'.format(2, 3, 5)` return?
A
2 + 3 = 5 B
2 + 5 = 3 C
{} + {} = {} D
Error
Analysis & Theory
Each `{}` is replaced by the corresponding argument passed to `format()`.
What is the result of `'{1} {0}'.format('world', 'Hello')`?
A
Hello world B
world Hello C
Hello Hello D
world world
Analysis & Theory
Using positional indexing, {1} is 'Hello' and {0} is 'world'.
How do you format a float to 2 decimal places?
A
`'{:.2}'.format(3.14159)` B
`'{:2f}'.format(3.14159)` C
`'{:.2f}'.format(3.14159)` D
`format(3.14159, '.2')`
Analysis & Theory
`{:.2f}` formats the float to 2 decimal places (e.g., 3.14).
What does f"Hello {name}" do?
A
Formats the string using variable `name` B
Creates an error C
Prints {name} literally D
Escapes the curly braces
Analysis & Theory
f-strings evaluate expressions inside `{}` using variable values.
What is the output of `f'{2 + 3}'`?
A
2 + 3 B
5 C
f'{2 + 3}' D
{2 + 3}
Analysis & Theory
f-strings evaluate expressions; 2 + 3 is 5.
Which method is more efficient for formatting strings in Python 3.6+?
A
format() B
concatenation C
f-strings D
% formatting
Analysis & Theory
f-strings are faster and more readable in Python 3.6 and above.
What will `'{name} is {age} years old'.format(name='Bob', age=25)` return?
A
Bob is 25 years old B
name is age years old C
25 is Bob years old D
Error
Analysis & Theory
Named placeholders are filled with keyword arguments.
Which formatting style is deprecated in favor of `format()` and f-strings?
A
% formatting B
join formatting C
html formatting D
template formatting
Analysis & Theory
`%` formatting (e.g., '%s') is an older style and is less preferred in modern Python.