【发布时间】:2015-05-06 00:10:49
【问题描述】:
假设我在 Python 中有一个多行字符串;我想将它转换为单行表示形式,其中行结尾写为\n 转义(和标签为\t 等) - 比如说,为了将它用作一些命令行参数。到目前为止,我认为 pprint.pformat 可以用于此目的 - 但问题是,我无法从这个单行表示转换回“正确的”多行字符串;这是一个例子:
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))
此示例使用 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 中是否有标准方法来实现这一点,例如 - 就像在示例中一样 - 我可以从多行转义单行,然后进行模板化,然后将模板化单行转换回多行线表示?
【问题讨论】:
-
为什么需要将行尾转换为转义序列?为什么不能使用原始字符串(
MYSTRTEMP)作为模板? -
谢谢,@univerio:“为什么你需要将行尾转换为转义序列”->“比如说,为了将它用作一些命令行参数”; “为什么你不能使用原始字符串作为模板” - 我可以,但我只是原则上感兴趣,如果有一个操作可以在模板的上下文中进行这种转换。干杯!