[英]Python – Print a character based on Unicode name stored as a string variable
I am trying to make a script that prints a set of characters based on their Unicode names (What I mean by 'Unicode name' is that I want to use the character's 'description', not the codepoint).我正在尝试制作一个脚本,该脚本根据其 Unicode 名称打印一组字符(我所说的“Unicode 名称”是我想使用字符的“描述”,而不是代码点)。
I understood that the standard way to do it for a single character is to do:我知道为单个字符执行此操作的标准方法是:
>>> print('\N{GREEK SMALL LETTER PHI}')
φ
My goal is to use a for loop that goes like this :我的目标是使用这样的 for 循环:
unicode_names = ['GREEK SMALL LETTER ALPHA', 'GREEK SMALL LETTER PHI']
for name in unicode_names:
char_name = "{{{0}}}".format(name)
print('\N' + char_name)
and the output would be: output 将是:
α
φ
The problem is that whatever I try, (so far), I can't print unicode character using a name stored as as string variable, be it by string concatenation or by using a .format()
method.问题是,无论我尝试什么,(到目前为止),我都无法使用存储为字符串变量的名称打印 unicode 字符,无论是通过字符串连接还是使用
.format()
方法。
phi = '\N{GREEK SMALL LETTER PHI}'
phi_name = "{{{0}}}".format('GREEK SMALL LETTER PHI')
print(phi)
print(phi_name)
print('\N' + phi_name)
When I try I get this kind of SyntaxError:当我尝试时,我得到了这种 SyntaxError:
print('\N' + phi_name)
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: malformed \N character escape
Should I use f-strings, or other kind of special strings?我应该使用 f 字符串还是其他类型的特殊字符串? Why
print('\N{GREEK SMALL LETTER PHI}')
is not interpreted the same as print('\N' + '{GREEK SMALL LETTER PHI}')
?为什么
print('\N{GREEK SMALL LETTER PHI}')
的解释与print('\N' + '{GREEK SMALL LETTER PHI}')
不同?
You're looking for the unicodedata.lookup
function.您正在寻找
unicodedata.lookup
function。
>>> import unicodedata
>>> unicodedata.lookup('GREEK SMALL LETTER PHI')
'φ'
Here's a demo of how to use unicodedata
:下面是如何使用
unicodedata
的演示:
import unicodedata
unicode_names = ['GREEK SMALL LETTER ALPHA', 'GREEK SMALL LETTER PHI']
for name in unicode_names:
print (name, unicodedata.lookup(name))
Does this work for you?这对你有用吗?
unicode_names = ['\N{GREEK SMALL LETTER ALPHA}', '\N{GREEK SMALL LETTER PHI}']
for name in unicode_names:
print(f"{name}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.