【问题标题】:Trying to print unicode characters to the console using string.format()尝试使用 string.format() 将 unicode 字符打印到控制台
【发布时间】:2011-12-09 22:34:33
【问题描述】:

下面是有问题的sn-p:

print '{:─^10}'.format('') # Print '─' character 10 times

我正在使用它来创建漂亮的控制台边框等。问题是,在我的 py 文件中使用 # coding UTF-8 运行它会给我:ValueError: Invalid conversion specification

如果我在 python shell 中运行相同的脚本,它会输出转义字符:'\xc4\xc4\xc4\x...'

我不知道如何(在我的脚本中)让它打印出 '─' 字符。如果我使用 print '─' 因为 UTF-8 编码,它可以打印 '─' 字符就好了,但由于某种原因它不允许它进入string.format() 函数。

有什么建议吗?我确信这可能很容易解决,但我对 python 编程非常陌生。

提前致谢。

【问题讨论】:

    标签: python unicode string-formatting unicode-string


    【解决方案1】:

    假设您使用的是 Python2,则需要使用 unicode (u'') 字符串:

    print u'{:─^10}'.format(u'')
    

    【讨论】:

    • 我不敢相信我错过了。我在 '{:─^10}' 前面尝试了 u,但我没有想到将它放在格式参数中。非常感谢!我知道这会很简单,哈哈
    猜你喜欢
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    相关资源
    最近更新 更多