Hi, there! how do you update a variable containing a string, so that the added string starts on a new line?(using plus equal operator, if possible)

For example in the code below, I want “Thank you for coming” to be printed on a different line than “Hello everyone” when I print string_1.
Thanks in advance

string_1= "Hello, everyone!"
string_2=" Thank you for coming."
string_1+=string_2
print(string_1)

If you want string_1 to be printed on a different line than string_2 you would:
Print string_1 to the console then print string_2 ex (in JS):

Console.log(string_1)
console.log(string_2)

Hello @byte3715880959, welcome to the forums! You’ve nearly got it with:

The only problem is that will print "Hello, everyone! Thank you for coming.". Since you want them on different lines, you may wish to concatenate the newline character "\n" as well.


A quick note on concatenating: you can concatenate as many strings as you like:

some_var  = "string_1" + " something else " + "another thing"
print(some_var)
#logs string_1 something else another thing
1 Like

Concatenation is very old school. We have a much more elegant method in, f-string

string1 = "Hello"
string2 = "World"
print (f"{string1}\n{string2}!")

Combine this with Python multi-line quotes and we can write it like so,

print (f'''{string1}
{string2}!''')
Hello
World!

Hi, thank you very much I now see how to do it, but at first it didn’t work when I tried to concatenate \n without quotes, and then I put them around the \n character and it worked. Does that mean that every time I want to use \n, I need to put quotes around it? I ask because in the example below I didn’t put quotes around \n and it still output it:

# Prints Hi! and I've been looking for you on different lines
`print("Hi!\n I've been looking for you.")`

The \n is still a string, so it has to be inside a string. For example, in your string, \n is still inside a string.

1 Like