Question Detail

COS 102 Python strings Objective Question

Question

What is the correct way to concatenate the string 'The answer is: ' with the number 42 in Python?
Options
A <code>'The answer is: ' + 42</code>
B <code>'The answer is: ' + str(42)</code>
Correct Answer
C <code>'The answer is: ' + int('42')</code>
D <code>'The answer is: ' + '42'</code>
Correct Answer

Option B is the correct answer.

Detailed Explanation

As explained in 'Avoid the TypeError', you cannot directly add a string and a number. The number must first be converted to a string using the str() function before concatenation. Option A would result in a TypeError. Option C converts '42' to an integer, which then cannot be concatenated with a string. Option D would work, but it assumes the number is already a string, not an integer as given in the question.

Hint

Remember the 'Mixing Types' warning and its solution for concatenation.

Question Info