planetp
planetp

Reputation: 16085

How can I create a single raw string from multiple literals in Python?

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?

Upvotes: 0

Views: 139

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122152

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'

Upvotes: 5

Related Questions