How to write string literals in python without avoiding them?

Is there a way to declare a string variable in python so that everything inside it is automatically escaped or has a literal character value?

I do not ask how to avoid quotes with a slash, which is obvious. What I'm asking for is a universal way to do everything in a string literal so that I don't have to manually go through and avoid everything for very large strings. Does anyone know of a solution? Thank!

+78
python string escaping
Jan 16 2018-11-11T00:
source share
6 answers

String literals:

>>> r'abc\dev\t' 'abc\\dev\\t' 
+95
Jan 16 2018-11-11T00:
source share

If you are dealing with very large strings, in particular multiline strings, remember the triple quotation syntax:

 a = r"""This is a multiline string with more than one line in the source code.""" 
+54
Jan 16 2018-11-11T00:
source share

There is no such thing. It sounds like you want something like โ€œhere docsโ€ in Perl and shells, but Python doesn't.

Using source strings or multi-line strings means thereโ€™s less to worry about. If you use a raw string, you still have to work with the terminal "\", and for any line-based solution, you have to worry about closing the ",", "or" "if it is included in your data.

That is, there is no way to have a string

  ' ''' """ " \ 

properly stored in any Python string literal without any type escaping internally.

+6
Jan 16 2018-11-11T00:
source share

Here you will find Python string literature documentation:

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

and here:

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

The simplest example is to use the 'r' prefix:

 ss = r'Hello\nWorld' print(ss) Hello\nWorld 
+2
Jan 16 2018-11-11T00:
source share

(Assuming you don't need to enter a string directly from Python code)

to work around the Andrew Dalke problem, simply enter a literal string in 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 what is in the text file, even if it is:

  ' ''' """ " \ 

Not fun and not optimal, but it can be useful, especially if you have 3 pages of code that would require character escaping.

+2
Mar 17 '16 at 6:19 06:19
source share

if the string is a variable, use. repr method on it:

 >>> s = '\tgherkin\n' >>> s '\tgherkin\n' >>> print(s) gherkin >>> print(s.__repr__()) '\tgherkin\n' 
0
Mar 28 '19 at 17:15
source share



All Articles