gpt4 book ai didi

python - 打印家庭表情符号,使用 U+200D 零宽度连接符,直接打印,对比通过列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:17:13 24 4
gpt4 key购买 nike

当通过 print 直接打印带有家庭表情符号的字符串时,我发现了一些意想不到的差异,当它在列表中时。下面的程序

family = '👨‍👩‍👧‍👧'
print(family)
print([family])

输出

👨‍👩‍👧‍👧
['👨\u200d👩\u200d👧\u200d👧']

我希望它什么时候输出

👨‍👩‍👧‍👧
['👨‍👩‍👧‍👧']

多字符字形的另一种情况

man_with_skin_tone_modifier = '👨🏿'
print(man_with_skin_tone_modifier)
print([man_with_skin_tone_modifier])

如我所料的输出:

👨🏿
['👨🏿']

这是为什么?


上下文:我在写 https://stackoverflow.com/a/49930688/1319998 的答案时发现了这一点,它在 OS X 上使用 Python 3.6.5。

最佳答案

如评论中所述,不同之处在于 print(family) 调用 str.__str__ 方法,而 print([family]) 调用 str.__repr__,它转义不可打印的 unicode 字符。

  1. print 函数使用 str 转换其(非关键字)参数。

  2. 在容器上调用 str(通常)会在它们的项上调用 repr。这主要是因为容器内的字符串很容易干扰容器本身的显示(例如使用换行符)。围绕 Python 3 的发布提出了一个改变这一点的 PEP,但是 quickly rejected .

  3. 在字符串上调用 repr 会转义任何不可打印的字符(但从 Python 3 开始,会保留其他非 ASCII Unicode 字符):参见 PEP-3138str.isprintable 的描述

Return true if all characters in the string are printable or the string is empty, false otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

可以找到 CPython 实现 here (搜索 unicode_repr 函数)。

关于python - 打印家庭表情符号,使用 U+200D 零宽度连接符,直接打印,对比通过列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49958287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com