【问题标题】:Capitalize doesn't work on special characters - Python大写不适用于特殊字符 - Python
【发布时间】:2015-02-27 16:40:01
【问题描述】:

我一直在尝试将大量字符串大写,其中一些以 utf-8 字符开头。 问题是,他们没有大写!

mystring = 'lucas'
mystring.capitalize() # returns 'Lucas'

mytring = 'æthelred'
mystring.capitalize() # returns 'æthelred'

与包含 `´^¨ 和字符 ð、þ 等的元音相同。 我该怎么做才能解决这个问题?

我实际上无权访问该字符串,我将它们放在其他地方,在一个文本文件中......

【问题讨论】:

  • mystring.decode("utf-8").capitalize()

标签: python string utf-8 character capitalize


【解决方案1】:

您省略了 u 。字符串需要定义为 python 的 unicode !

>>> mytring = u"æthelred"
>>> print mytring.capitalize()
Æthelred

python 3 中,默认情况下字符串是 unicode 你不需要 u

>>> "æthelred".capitalize()
'Æthelred'

【讨论】:

  • 这个答案对于 python 2.x 是正确的。在 python 3.x 中,字符串默认是 unicode,所以 Leandro 的代码应该可以正常工作
  • @stochastic 是的,谢谢提醒!我会更新答案
  • 当字符串已经在变量中时,如何将其定义为 unicode?抱歉,对此很陌生。
  • @LeandroLyra 只需使用unicode 函数:>>> unicode('abc') u'abc'
【解决方案2】:

如果您使用的是 Python 2,这也可以。在文件的顶部放置:

from __future__ import unicode_literals

这将强制字符串的行为类似于 Python 3,默认情况下使它们成为 unicode。

【讨论】:

  • 这似乎不起作用,有一些东西无法以这种方式解码。我也在文件开头声明了utf-8,这应该不是问题。
猜你喜欢
  • 2019-05-20
  • 1970-01-01
  • 2014-08-09
  • 2016-03-03
  • 1970-01-01
  • 2016-09-13
  • 2019-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多