Backslash in String Formatting


#1

I don’t remember being taught a backslash in between two strings for printing.
The only thing I remember is \n to create a break. Is this the same thing?

print "Ah, so your name is %s, your quest is %s, "
“and your favorite color is %s.” % (name, quest, color)

For some reason this post is deleting the backslash as well. It’s supposed to be after the first string.

I tried removing the backslash and it gave me this error:
Traceback (most recent call last):
File “python”, line 6, in
TypeError: not all arguments converted during string formatting


#2

Hi @hypnagogia3,

The backslash that you removed is a line continuation character. Without it, this string is broken …

"Ah, so your name is %s, your quest is %s, and your favorite color is %s.”

#3

Hello,

Thank you, so I’m wondering then why can’t the string be one long continuous sentence?
Is it because it’s too long and that’s why you need to break the sentence into two strings and add that backslash in between? I’m understanding it this way if I’m correct. If that’s the case what is the limit to how long one string can be?

Thank you!


#4

It was broken into two lines so that users could see the code without scrolling across the page, and not because it was too long for the Python interpreter. The interpreter can even handle strings that contain many thousands of characters, as long as it all fits within available memory.


#5

Thank you! That makes perfect sense.


#6