在 Python 中的多行和单行(带转义换行符)字符串表示之间转换?
Converting between multiline and single-line (with escaped linebreaks) string representations in Python?
假设我在 Python 中有一个多行字符串;我想将它转换为单行表示,其中行结尾写为 \n
转义符(和制表符为 \t
等) - 比如说,为了将它用作一些命令行参数.到目前为止,我认为 pprint.pformat
可以用于此目的 - 但问题是,我无法从这种单行表示形式转换回 "proper" 多行字符串;这是一个例子:
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)
#
MYSTR = string.Template(testsingle).substitute({'FNAME': 'Bobby'})
print("--Testing single-line replaced:")
print(MYSTR)
print("--Testing going back to multiline - cannot:")
print("%s"%(MYSTR))
此示例具有 Python 2.7 输出:
$ 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'
一个问题是单行表示似乎在字符串本身中包含 '
单引号 - 第二个问题是我无法从该表示返回到正确的多行字符串。
Python 中是否有标准方法来实现这一点,这样一来-如示例中-我可以从多行转义为转义单行,然后进行模板化,然后转换模板化的单行- 线回到多线表示?
要从字符串的 repr
(这是 pformat
给你的字符串)到实际的字符串,你可以使用 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'
转换为 repr
只是为了转换回来可能不是实现您最初目标的好方法,但这就是您要做的。
假设我在 Python 中有一个多行字符串;我想将它转换为单行表示,其中行结尾写为 \n
转义符(和制表符为 \t
等) - 比如说,为了将它用作一些命令行参数.到目前为止,我认为 pprint.pformat
可以用于此目的 - 但问题是,我无法从这种单行表示形式转换回 "proper" 多行字符串;这是一个例子:
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)
#
MYSTR = string.Template(testsingle).substitute({'FNAME': 'Bobby'})
print("--Testing single-line replaced:")
print(MYSTR)
print("--Testing going back to multiline - cannot:")
print("%s"%(MYSTR))
此示例具有 Python 2.7 输出:
$ 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'
一个问题是单行表示似乎在字符串本身中包含 '
单引号 - 第二个问题是我无法从该表示返回到正确的多行字符串。
Python 中是否有标准方法来实现这一点,这样一来-如示例中-我可以从多行转义为转义单行,然后进行模板化,然后转换模板化的单行- 线回到多线表示?
要从字符串的 repr
(这是 pformat
给你的字符串)到实际的字符串,你可以使用 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'
转换为 repr
只是为了转换回来可能不是实现您最初目标的好方法,但这就是您要做的。