144

Is there a way to declare a string variable in Python such that everything inside of it is automatically escaped, or has its literal character value?

I'm not asking how to escape the quotes with slashes, that's obvious. What I'm asking for is a general purpose way for making everything in a string literal so that I don't have to manually go through and escape everything for very large strings.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
kjakeb
  • 6,810
  • 5
  • 20
  • 34
  • See also: [How can I put an actual backslash in a string literal (not use it for an escape sequence)?](https://stackoverflow.com/questions/3380484/) – Karl Knechtel Aug 07 '22 at 07:58

6 Answers6

181

Raw string literals:

>>> r'abc\dev\t'
'abc\\dev\\t'
SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • 2
    Please note that a raw string literal [cannot end with a backslash (really, an odd number of backslashes)](https://stackoverflow.com/questions/647769/) and [can only include the quote character if it is preceded by a backslash, which will be included literally](https://stackoverflow.com/questions/4630465/how-to-include-a-quote-in-a-raw-python-string). – Karl Knechtel Aug 07 '22 at 04:36
97

If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:

a = r"""This is a multiline string
with more than one line
in the source code."""
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • 1
    Does this construct introduce line break characters? That is, the variable `a` will contain a string with two line break characters? – MadPhysicist Apr 28 '17 at 19:28
  • 8
    @MadPhysicist: Yes, the resulting string will contain two newlines in the above case. – Greg Hewgill Apr 28 '17 at 19:33
  • Understood. And if a 'split()' is used on this string, will it split by lines by default? – MadPhysicist Apr 28 '17 at 19:37
  • 3
    @MadPhysicist The default for .split() is to split by whitespace, and newlines are whitespace. – Greg Hewgill Apr 29 '17 at 02:41
  • Isn't that a comment? – Aikanáro May 02 '17 at 14:36
  • @Aikanáro I don't think it's a docstring (what I assume you mean by comment - comments use #) when you use it in assignment to a variable? – toonarmycaptain Jul 30 '17 at 16:26
  • 1
    I've used this before and it works fine. Two things to be aware: indentation (spaces) on the other lines are included which is desirable; if the long string happens to be terminated with `"` no good, because the whole thing will end up with `"""" ` which is a syntax error. – Nagev Jan 09 '19 at 15:30
  • I guess this is a *raw-string triple-quote literal*. – Brent Bradburn Mar 10 '20 at 14:39
  • If your string needs to start or end with double quotes then use triple single quotes ''' instead of triple double quotes """. – Rick May 19 '21 at 05:17
13

There is no such thing. It looks like you want something like "here documents" in Perl and the shells, but Python doesn't have that.

Using raw strings or multiline strings only means that there are fewer things to worry about. If you use a raw string then you still have to work around a terminal "\" and with any string solution you'll have to worry about the closing ", ', ''' or """ if it is included in your data.

That is, there's no way to have the string

 '   ''' """  " \

properly stored in any Python string literal without internal escaping of some sort.

Andrew Dalke
  • 14,889
  • 4
  • 39
  • 54
  • 1
    What is the issue with the backslash in your example? Or in general? How does it interact with the raw string? – user2962533 Jun 01 '22 at 09:19
8

You will find Python's string literal documentation here:

http://docs.python.org/tutorial/introduction.html#strings

and here:

http://docs.python.org/reference/lexical_analysis.html#literals

The simplest example would be using the 'r' prefix:

ss = r'Hello\nWorld'
print(ss)
Hello\nWorld
Grr
  • 15,553
  • 7
  • 65
  • 85
ʇsәɹoɈ
  • 22,757
  • 7
  • 55
  • 61
2

(Assuming you are not required to input the string from directly within Python code)

to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;

input_ = '/directory_of_text_file/your_text_file.txt' 
input_open   = open(input_,'r+')
input_string = input_open.read()

print input_string

This will print the literal text of whatever is in the text file, even if it is;

 '   ''' """  “ \

Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.

Jeff Hykin
  • 1,846
  • 16
  • 25
1

Use print and repr:

>>> s = '\tgherkin\n'

>>> s
'\tgherkin\n'

>>> print(s)
    gherkin

>>> repr(s)
"'\\tgherkin\\n'"

# print(repr(..)) gets literal

>>> print(repr(s))
'\tgherkin\n'

>>> repr('\tgherkin\n')
"'\\tgherkin\\n'"

>>> print('\tgherkin\n')
    gherkin

>>> print(repr('\tgherkin\n'))
'\tgherkin\n'
markling
  • 1,232
  • 1
  • 15
  • 28