PPrint 不工作(Python)?

PPrint not working (Python)?

我正在尝试在字典上使用 Python 的 pprint,但由于某种原因它不起作用。这是我的代码(我使用 PyCharm Pro 作为我的 IDE):`

from pprint import pprint
message = "Come on Eileen!"
count = {}

for character in message:
    count.setdefault(character, 0)
    count[character] += 1

pprint(count)

这是我的输出:

{' ': 2, '!': 1, 'C': 1, 'E': 1, 'e': 3, 'i': 1, 'l': 1, 'm': 1, 'n': 2, 'o': 2}

如有任何帮助,我们将不胜感激。

输出完全正确且符合预期。来自 pprint module documentation:

The formatted representation keeps objects on a single line if it can, and breaks them onto multiple lines if they don’t fit within the allowed width.

大胆强调我的。

您可以将 width 关键字参数设置为 1 以强制在单独的行上打印每个键值对:

>>> pprint(count, width=1)
{' ': 2,
 '!': 1,
 'C': 1,
 'E': 1,
 'e': 3,
 'i': 1,
 'l': 1,
 'm': 1,
 'n': 2,
 'o': 2}

我在练习时遇到了同样的问题,然后我意识到我在 运行 一次又一次地使用旧的 characterCount.py 而不是 运行 宁用新的漂亮角色 Count.py 文件。 尝试单击顶部的 运行 按钮并选择正确的文件并再次 运行。

您必须指定第二个参数,即

pprint.pprint(count, width=1)

或者你的情况

pprint(count, width=1)

输出:

{' ': 2,
 '!': 1,
 'C': 1,
 'E': 1,
 'e': 3,
 'i': 1,
 'l': 1,
 'm': 1,
 'n': 2,
 'o': 2}