-1
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.

Noob
  • 71
  • 9
  • 2
    `"+ last +"` isn't a string. `" ["` and `"] "` are the strings. You need to think of what quotes are matching what other quotes. – Carcigenicate May 14 '21 at 16:12
  • There are different ways to concat variables into a string in Python. One easier way is f-string formatting: `msg = f"John [{last}]"`. – sandertjuh May 14 '21 at 16:12
  • in python using the `+` operator with strings is synonymous with "concatenate" – Aaron May 14 '21 at 16:21

3 Answers3

1

Think of it like this.

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

If it helps, add print(msg) after each assignment to msg and see how it develops.

There are many, many, many other ways to do this. See How do I put a variable inside a string?

tripleee
  • 175,061
  • 34
  • 275
  • 318
1
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.

Kevin
  • 398
  • 2
  • 7
  • Ohh, I didnt't realise that the square brackets were the strings. I thought the "+ last +" were the strings and had trouble understanding the syntax. I see. Thank you – Noob May 14 '21 at 17:47
0

The square brackets are themselves already a string, so they don't act like normal code entities. You need the plus sign to add the strings you have created into one string.

first = "John"
last = "Smith"
left_b = " ["
right_b ="] "

msg = first + left_b + last + right_b
print(msg)

This is the same thing as what you are trying to do but everything is a variable.

It can also be written like this to avoid plus signs using string injection:

last = "Smith"
msg = "John {}".format(last)