gpt4 book ai didi

python - 在 Python 中存储为变量的字符串上使用 u'string'

转载 作者:行者123 更新时间:2023-12-01 01:32:39 25 4
gpt4 key购买 nike

作为 Python 2.7 的法国用户,我正在尝试在 Python 控制台中正确打印包含“é”、“è”、“à”等重音符号的字符串。

我已经知道在字符串的显式值之前使用 u 的技巧,例如:

print(u'Université')

正确打印最后一个字符。

现在,我的问题是:如何对存储为变量的字符串执行相同的操作?

确实,我知道我可以执行以下操作:

mystring = u'Université'
print(mystring)

但问题是 mystring 的值必然会传递到 SQL 查询中(使用 psycopg2 ),因此我无法存储 u mystring 的值内.

所以我怎么能做类似的事情“打印 mystring 的 unicode 值”?

最佳答案

u 标记不是值的一部分,它只是一个类型指示符。要将字符串转换为 Unicode 字符串,您需要知道编码。

unicodestring = mystring.decode('utf-8')  # or 'latin-1' or ... whatever

要打印它,您通常(在 Python 2 中)需要转换回系统在输出文件句柄上接受的任何内容:

print(unicodestring.encode('utf-8'))  # or 'latin-1' or ... whatever

Python 3 通过将 Unicode 字符串和(现在称为)bytes 对象分开来澄清(尽管没有直接简化)这种情况。

关于python - 在 Python 中存储为变量的字符串上使用 u'string',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52699494/

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