Reputation: 38619
Let's say I have a multiline string in Python; I would like to convert it to a single-line representation, where the line endings are written as \n
escapes (and tabs as \t
etc) - say, in order to use it as some command line argument. So far, I figured that pprint.pformat
can be used for the purpose - but the problem is, I cannot convert from this single-line representation back to a "proper" multi-line string; here's an example:
import string
import pprint
MYSTRTEMP = """Hello $FNAME!
I am writing this.
Just to test.
"""
print("--Testing multiline:")
print(MYSTRTEMP)
print("--Testing single-line (escaped) representation:")
testsingle = pprint.pformat(MYSTRTEMP)
print(testsingle)
# http://stackoverflow.com/questions/12768107/string-substitutions-using-templates-in-python
MYSTR = string.Template(testsingle).substitute({'FNAME': 'Bobby'})
print("--Testing single-line replaced:")
print(MYSTR)
print("--Testing going back to multiline - cannot:")
print("%s"%(MYSTR))
This example with Python 2.7 outputs:
$ python test.py
--Testing multiline:
Hello $FNAME!
I am writing this.
Just to test.
--Testing single-line (escaped) representation:
'Hello $FNAME!\n\nI am writing this.\n\nJust to test.\n'
--Testing single-line replaced:
'Hello Bobby!\n\nI am writing this.\n\nJust to test.\n'
--Testing going back to multiline - cannot:
'Hello Bobby!\n\nI am writing this.\n\nJust to test.\n'
One problem is that the single-line representation seems to include the '
single quotes in the string itself - second problem is that I cannot go back from this representation back to a proper multiline string.
Is there a standard method in Python to achieve this, such that - as in the example - I could go from multi-line to escaped single-line, then do templating, then convert the templated single-line back to a multi-line representation?
Upvotes: 0
Views: 1611
Reputation: 20518
To go from the repr
of a string (which is what pformat
gives you for a string) to the actual string, you can use ast.literal_eval
:
>>> repr(MYSTRTEMP)
"'Hello $FNAME!\\n\\nI am writing this.\\n\\nJust to test.\\n'"
>>> ast.literal_eval(repr(MYSTRTEMP))
'Hello $FNAME!\n\nI am writing this.\n\nJust to test.\n'
Converting to repr
just to convert back is probably not a good way to accomplish your original goal, though, but this is how you would do it.
Upvotes: 2