0

I want to combine adjacent strings to a single 'raw' string in Python, e.g.

>>> s = (
...     r"foo\tbar\n"
...     "baz\tqux\n")

However this only makes the first part 'raw':

>>> print(s)
foo\tbar\nbaz   qux

>>>

Can I somehow propagate the 'r' to all adjacent literals?

0

1 Answer 1

5

The r prefix is part of the literal notation, not part of the resulting string object.

Use it on each line, there is no shortcut here:

s = (
    r"foo\tbar\n"
    r"baz\tqux\n")

If you really have a lot of these and find all those r prefixes that cumbersome, you could use a raw multiline string (triple quoting) and remove the newlines:

s = ''.join(r"""
foo\tbar\n
baz\tqux\n
""".splitlines())

Note that this won't remove initial whitespace, so you'd either have to start each line at column 0 or use textwrap.dedent() to remove consistent leading whitespace for you:

from textwrap import dedent

s = ''.join(dedent(r"""
    foo\tbar\n
    baz\tqux\n
""").splitlines())

Quick demo:

>>> s = (
...     r"foo\tbar\n"
...     r"baz\tqux\n")
>>> s
'foo\\tbar\\nbaz\\tqux\\n'
>>> s = ''.join(r"""
... foo\tbar\n
... baz\tqux\n
... """.splitlines())
>>> s
'foo\\tbar\\nbaz\\tqux\\n'
>>> from textwrap import dedent
>>> s = ''.join(dedent(r"""
...     foo\tbar\n
...     baz\tqux\n
... """).splitlines())
>>> s
'foo\\tbar\\nbaz\\tqux\\n'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.