2

It's great that I can write

s = r"some line\n"

but what is the functional equivalent to preprending with r? For example:

s = raw_rep( s )

2 Answers 2

3

There isn't one. The r is an integral part of the string literal token, and omitting it is a lossy operation.

For example, r'\n', r'\12' and r'\x0a' are three different strings. However, if you omit the r, they become identical, making it impossible to tell which of the three it was to begin with.

For this reason, this is no method that would reconstruct the original string 100% of the time.

Sign up to request clarification or add additional context in comments.

3 Comments

I understand your example. Is there a workaround? What if I don't care what the original string is, is there a workaround?
@Cam.Davidson.Pilon: What exactly are you trying to do?
json.loads some data with escape characters. ex: json.loads( """{"data":"aefea\n"}""" ) will fail.
2
def raw_rep(s):
    quote = '"' if "'" in s else "'"
    return 'r' + quote + s + quote

>>> print raw_rep(r'some line\n')
r'some line\n'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.