[英]How do I use both single and double quotes in a python string
I am going a little crazy trying out all combinations. 我要疯狂尝试所有组合。 I need a string variable whose value is set to: r'" a very long string \\r"' This long string is given across multiple lines. 我需要一个字符串变量,其值设置为: r'“一个非常长的字符串\\ r”'这个长字符串在多行中给出。 My code looks like this: 我的代码如下所示:
str = r'" a very
long
string \r"'
This is introducing "\\n" in the str variable. 这是在str变量中引入“ \\ n”。 I tried using this syntax """ ...""" too. 我也尝试使用这种语法“”“ ...”“”。 But I get a syntax error. 但是我收到语法错误。 Can someone help me please ? 有人能帮助我吗 ? I saw the other Qs on stackoverflow, they don't seem to match this requirement. 我在stackoverflow上看到了其他Q,它们似乎不符合此要求。
You can use multiple string literals ; 您可以使用多个字符串文字 ; as long as they are on the same logical line they'll be concatenated to one long string. 只要它们在同一逻辑行上,它们就会被连接为一个长字符串。 You can extend the logical line with paretheses: 您可以使用paretheses扩展逻辑行:
yourstr = (
'" a very'
'long '
r'string \r"')
Note that I mixed string literal types here. 请注意,我在这里混合了字符串文字类型 。 The first two parts are normal string literals, the latter part is a raw string literal so you don't have to double the \\
in \\r
. 前两个部分都是正常的字符串文字,后半部分是一个原始字符串字面量,所以你不必加倍\\
中\\r
。 If you really wanted to have a CR carriage return, omit the r
prefix. 如果您确实想返回CR回车,请省略r
前缀。
Demo: 演示:
>>> yourstr = (
... '" a very'
... 'long '
... r'string \r"')
>>> yourstr
'" a verylong string \\r"'
>>> print yourstr
" a verylong string \r"
The Python compiler concatenates adjacent string literals. Python编译器连接相邻的字符串文字。 The trick is to tell it that it should be considered a single line of code. 诀窍是告诉它应该视为一行代码。
S = ('" a very '
'long '
r'string \r"')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.