以换行符美观地打印元组

3
>>> print(("hello\nworld", "hello2"))
('hello\nworld', 'hello2')

如何使它打印出来:
('hello
world', 'hello2')

我的意思是它不能将 \n 打印为符号,而是要实现这个符号并换行。

Python版本为 3.4

我尝试使用 pprint 但它做了同样的事情:

>>> import pprint
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(("hello\nworld"))
'hello\nworld'

我认为你不能同时打印数据结构并评估数据。你必须自己实现它。 - Peter Wood
6个回答

2
没有任何东西可以自动地为您完成这种打印。Python容器默认使用repr将其内容转换为字符串(即使您在容器上调用str而不是repr)。这是为了避免像["foo, bar", "baz"]这样的歧义(如果没有引号,则无法确定列表中有两个还是三个项目)。
但是,您可以自己格式化元组,并获得所需的输出:
print("({})".format(", ".join(tup)))

1
如果你不想要括号和逗号,那么只需要使用*运算符即可:
>>> t = ("hello\nworld", "hello2")
>>> print(*t)
hello
world hello2

如果您想要打印括号和逗号,但也将 '\n' 转换为换行符,则需要编写该行为的代码,正如 @Peter 所说。
>>> print('(' + ', '.join(t) + ')')
(hello
world, hello2)

没有注意到您在每个字符串周围使用了 '。如果您想要这样做,请使用@Jeremie的答案。您必须确保按您想要的方式格式化元组 - "('1','2')""('1', '2')" 是不同的。 - TigerhawkT3
你可以通过执行 print(*t, sep=', ') 来获取逗号。 - kaya3

0

编写:

print("('Hello\nworld', 'hello2')")

会直接打印:

('hello
world', 'hello2')

如果您只是想在字符串中插入一个新行,请使用以下代码:
print("Line1\nLine2")

\n 是转义序列,用于表示换行符,终止当前行并标识下一行的开始。

如果要将其与您拥有的代码进行比较,则应注意“”符号的位置,这些符号表示字符串的开头和结尾。


0
>>> t = ("hello\nworld", "hello2")
>>> print '({})'.format(', '.join("'{}'".format(value) for value in t))
('hello
world', 'hello2')

如果字符串包含'标记,则此方法将不正确。

请注意,Python的格式化功能可以巧妙地处理包含引号的字符串。


0

0
这是一个来自 Ansible 输出的更复杂的例子,让我感到很烦恼:
import pprint

f={
    "failed": True,
    "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object' has no attribute 'uid'\n\nThe error appears to have been in '/usr/local/etc/ansible/roles/singleplatform-eng.users/tasks/main.yml': line 7, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Per-user group creation\n  ^ here\n"
    }

def ppdump(data):
    print pprint.pformat(data, indent=4, width=-1).replace('\\n', '\n')

ppdump(f)
{   'failed': True,
    'msg': "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'dict object'
has no attribute 'uid'

The error appears to have been in '/usr/local/etc/ansible/roles/singleplatform-eng.users/tasks/main.yml': line 7, column 3, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:


- name: Per-user group creation
  ^ here
"}

问题在于pprint会转义换行符,所以我只需要将它们取消转义即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接