How to write string literals in Python without having to escape them?

Question:

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.

Asked By: kjakeb

||

Answers:

Raw string literals:

>>> r'abcdevt'
'abc\dev\t'
Answered By: SilentGhost

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."""
Answered By: Greg Hewgill

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'HellonWorld'
print(ss)
HellonWorld
Answered By: ʇsәɹoɈ

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.

Answered By: Andrew Dalke

(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.

Answered By: Jeff Hykin

Use print and repr:

>>> s = 'tgherkinn'

>>> s
'tgherkinn'

>>> print(s)
    gherkin

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

# print(repr(..)) gets literal

>>> print(repr(s))
'tgherkinn'

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

>>> print('tgherkinn')
    gherkin

>>> print(repr('tgherkinn'))
'tgherkinn'
Answered By: markling
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.