How to Write String Literals in Python Without Having to Escape Them

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

Raw string literals:

>>> r'abc\dev\t'
'abc\\dev\\t'

String literals without having to escape special characters?

There's no equivalent to the triple-quote; string literals must always use escapes for special characters.

Perhaps the best thing to do would be to put your HTML into a file separate from your source, then create the string using -[NSString initWithContentsOfFile:encoding:error:] (or the related initWithContentsOfURL:...).

How can I put an actual backslash in a string literal (not use it for an escape sequence)?

To answer your question directly, put r in front of the string.

final= path + r'\xulrunner.exe ' + path + r'\application.ini'

But a better solution would be os.path.join:

final = os.path.join(path, 'xulrunner.exe') + ' ' + \
os.path.join(path, 'application.ini')

(the backslash there is escaping a newline, but you could put the whole thing on one line if you want)

I will mention that you can use forward slashes in file paths, and Python will automatically convert them to the correct separator (backslash on Windows) as necessary. So

final = path + '/xulrunner.exe ' + path + '/application.ini'

should work. But it's still preferable to use os.path.join because that makes it clear what you're trying to do.

ignoring backslash character in python

You don't have fwd in b. You have wd, preceded by ASCII codepoint 0C, the FORM FEED character. That's the value Python puts there when you use a \f escape sequence in a regular string literal.

Double the backslash if you want to include a backslash or use a raw string literal:

b = '\\fwd'
b = r'\fwd'

Now a in b works:

>>> 'fwd' in '\\fwd'
True
>>> 'fwd' in r'\fwd'
True

See the String literals documentation:

Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:

[...]

\f ASCII Formfeed (FF)

How to ignore backslashes as escape characters in Python?

Preface the string with r (for "raw", I think) and it will be interpreted literally without substitutions:

>>> # Your original
>>> print('''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')

/\/\/\/\/\
\/\/\/\/\/

>>> # as a raw string instead
>>> print(r'''
... /\\/\\/\\/\\/\\
... \\/\\/\\/\\/\\/
... ''')

/\\/\\/\\/\\/\\
\\/\\/\\/\\/\\/

These are often used for regular expressions, where it gets tedious to have to double-escape backslashes. There are a couple other letters you can do this with, including f (for format strings, which act differently), b (a literal bytes object, instead of a string), and u, which used to designate Unicode strings in python 2 and I don't think does anything special in python 3.



Related Topics



Leave a reply



Submit