Question Detail

COS 102 Python strings Objective Question

Question

Given the code:
name = 'John'
greeting = 'Hello, ' + name + '!'
What will be the final value of greeting?
Options
A <code>'Hello, John!'</code>
Correct Answer
B <code>'Hello,John!'</code>
C <code>'Hello, John !'</code>
D <code>'Hello, John ! '</code>
Correct Answer

Option A is the correct answer.

Detailed Explanation

The concatenation starts with 'Hello, '. Then 'John' is added. Finally, '!' is added. The space after the comma is part of 'Hello, ', and there is no space after 'John' or before '!'. So, 'Hello, ' + 'John' + '!' results in 'Hello, John!'.

Hint

Trace the concatenation step-by-step and observe where spaces are explicitly included in the string literals.

Question Info