简体   繁体   English

EOL 错误 - 在 Python 字符串中转义换行符

[英]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.我希望将文本块交给 API。但是,如果我尝试另存为变量,我不能因为 python 不会让我处理文本。 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.我尝试了下面的代码来克服 EOL 错误,但它没有用。 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)我想自动执行它而不是手动添加反斜杠,因为提示是文本,输入时会更改为 api。这没有区别 def escape_newline(string): return string.replace("\n", "\\n") 提示= scape_newline(提示符)

print (prompt)

This comes up with:这带来了:
prompt = (f"xxxx ^ SyntaxError: EOL while scanning string literal提示 = (f"xxxx ^ SyntaxError: EOL while scanning string literal

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM