简体   繁体   English

如何在python字符串中同时使用单引号和双引号

[英]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.

相关问题 如何格式化带有双引号和单引号的python字符串 - How to format python string with both double and single quotes 如何创建包含单引号和双引号 python 的字符串? - How can I create a string that contains both single and double quotes python? 如何在 python 数组中用双引号替换单引号而不替换 json 值中的单引号? - How do I replace single quotes with double quotes in a python array without replacing the single quotes in the json values? 如何使用双引号和单引号在python中定义字符串 - How to define a string in python with double and single quotes 如何轻松使用包含单引号和双引号的python字符串? - How to easily work with python strings containing both single and double quotes? 如何在Python中的字符串中双引号内显示​​单引号 - How to display single quotes inside double quotes in string in python 如何转换字符串python单引号双引号 - How to convert a string python single quotes double quotes 如何将Python列表中带单引号的字符串元素转为双引号 - How to convert string elements with single quotes to double quotes in a Python list Python如何将单引号转换为双引号以格式化为json字符串 - Python how convert single quotes to double quotes to format as json string 如何在双引号中打印字符串? (不打印双引号) - How do I print a string in double quotes? (NOT PRINT DOUBLE QUOTES)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM