pythonresultsetsquare-bracketquotation-marks

How to print a value from a variable in square brackets?


last= "smith"

I am trying to print this line: John [Smith].

The answer is

last = "Smith"
msg = "John" + " ["+ last +"] "
print(msg)

But I don't understand why the answer is like this. Why do I need the plus signs? Won't the quotation marks in the square brackets cause "+ last +" to become a string instead of printing out the value? I have tried looking through my notes and am unable to understand the reasoning behind.


Solution

  • msg = "John" + " ["+ last +"] "
    

    Python interprets quotes as a string delimiter - anything inside quotes is treated as a string, not as python code.

    So here, " [" is a string, so the plus is required for string concatenation.