【问题标题】:Converting between multiline and single-line (with escaped linebreaks) string representations in Python?在 Python 中的多行和单行(带有转义的换行符)字符串表示之间转换?
【发布时间】: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:“为什么你需要将行尾转换为转义序列”->“比如说,为了将它用作一些命令行参数”; “为什么你不能使用原始字符串作为模板” - 我可以,但我只是原则上感兴趣,如果有一个操作可以在模板的上下文中进行这种转换。干杯!

标签: python string multiline


【解决方案1】:

要从字符串的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 只是为了转换回来可能不是实现您最初目标的好方法,但您会这样做。

【讨论】:

  • 我知道有些东西——我以前用过repr,但这次完全忘记了:) ast.literal_eval 是我正在寻找的东西,不过...非常感谢,@ univerio - 干杯!
猜你喜欢
  • 2017-09-06
  • 2016-02-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多