简体   繁体   中英

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. My code looks like this:

str = r'" a very 
      long 
      string \r"'

This is introducing "\\n" in the str variable. 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.

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:

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 . If you really wanted to have a CR carriage return, omit the r prefix.

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. The trick is to tell it that it should be considered a single line of code.

S = ('" a very '
     'long '
     r'string \r"')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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