Search code examples
error-handlingeol

EOL error - Escape Newline Characters in a Python String


I wish to hand chunks of text to an API. However, I cant as python wont let me handle the text if I try saving as a variable. How do I do it? Thank you

prompt = (f"xxxx
xxxx
xxxxx
xxxx
xxxx")

I tried code below to overcome the EOL error but it didnt work. I want to do it automatically not manually add backslashes as prompt is text which will change for input to an api. This made no difference def escape_newline(string): return string.replace("\n", "\\n") prompt= scape_newline(prompt)

print (prompt)

This comes up with:
prompt = (f"xxxx ^ SyntaxError: EOL while scanning string literal


Solution

  • Use triple strings instead of single ones. That allows for strings to take place over multiple lines :)

    prompt = (f"""xxxx
    xxxx
    xxxxx
    xxxx
    xxxx""")
    print(prompt)