我一直想将''
输出为'\U0001f604'
而不是笑脸,但似乎无法实现。
我尝试使用repr()
,但它给了我这个结果:'\xf0\x9f\x98\x84'
。目前它输出的是笑脸,而不是我想要的结果。使用encode('unicode_escape')
会给出一个UnicodeDecodeError
。
这个笑脸作为字符串传递给了Python中的一个类方法。例如:"我很开心"
我一直想将''
输出为'\U0001f604'
而不是笑脸,但似乎无法实现。
我尝试使用repr()
,但它给了我这个结果:'\xf0\x9f\x98\x84'
。目前它输出的是笑脸,而不是我想要的结果。使用encode('unicode_escape')
会给出一个UnicodeDecodeError
。
这个笑脸作为字符串传递给了Python中的一个类方法。例如:"我很开心"
另一个解决方案是使用名称别名,并使用字符串文字\N
来打印它们。
print('\N{grinning face with smiling eyes}')
当前名称别名列表可在此找到:https://unicode.org/Public/15.0.0/ucd/UnicodeData-15.0.0d6.txt
或者在这里查看所有文件夹:https://unicode.org/Public/
>>> print u'\U0001f604'.encode('unicode-escape')
\U0001f604
我找到了问题的解决方案。
我写了以下代码:
#convert to unicode
teststring = unicode(teststring, 'utf-8')
#encode it with string escape
teststring = teststring.encode('unicode_escape')
unicode
是内置的,.encode()
是字符串函数 - 不需要导入任何包。 - Jan Silabytes.decode(b'\xf0\x9f\x98\x84', 'utf8')
可能是 Python 3 版本中类似上面 unicode
调用的暗示。如果你知道你有一个 bytes
对象,你可以直接在它上面调用 decode
来获取一个 (unicode) str
对象,例如 b'\xf0\x9f\x98\x84'.decode('utf8')
。 - Sam Mason# -*- coding: UTF-8 -*-
在您的代码中加入这段代码,您将能够打印Unicode字符。以下代码可以帮助你简单地打印出一个表情符号:
# -*- coding: UTF-8 -*-
import re
# string = 'Anything else that you wish to match, except URLs http://url.org'
string = 'Anything else that you wish to match'
matches = re.search(r'^(((?!http|https).)+)$', string)
if matches:
print(matches.group(1)+ " is a match ")
else:
print(' Sorry! No matches! Something is not right!')
Sorry! No matches! Something is not right!
Anything else that you wish to match is a match
print(u'\U0001f604')
因此,您将获得输出结果
所以只需在字符串开头加上u
。
希望这能帮到你。
>>> print '%r' % u'\U0001f604'
u'\U0001f604'
print('\N{thumbs up sign}')
可以正常工作。 - nth-attempt