gpt4 book ai didi

python - 方法在 Python 2 中对 Unicode 友好吗?

转载 作者:太空狗 更新时间:2023-10-30 03:00:24 25 4
gpt4 key购买 nike

我在我的代码中使用这一行来计算字符串中的大写字母:

text = "Áno"
count = sum(1 for c in text if c.isupper())

此代码返回 0,但我期望返回 1(因为“Á”是大写)如何计算带有 Unicode 字符的大写字母?

最佳答案

对于 python 2 你需要添加一个 u,你的字符串实际上不是 unicode:

text = u"Áno"

您也可以将表达式写成 count = sum(c.isupper() for c in text)c.isupper() 将返回 True 或 False,因此1 或 0。

In [1]: text = "Áno"

In [2]: count = sum(c.isupper() for c in text)

In [3]: count
Out[3]: 0
In [4]: text = u"Áno"
In [5]: count = sum(c.isupper() for c in text)
In [6]: count
Out[6]: 1
In [7]: text = "Áno".decode("utf-8")
In [8]: count = sum(c.isupper() for c in text)
In [9]: count
Out[9]: 1

关于python - 方法在 Python 2 中对 Unicode 友好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29458980/

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