python - 对具有无效 ASCII 的字符串进行 title() 方法

标签 python non-ascii-characters

我有一个姓氏列表,但其格式不正确。每个名字都是用 Camel 风格写的 -.- 我试图用 title() 方法让它看起来更干净。

s = 'KroGer'
s = s.title()
print s
>Kroger

这个效果很好。但是当我的名字中有非 ASCII 字母时:

s = 'KRöGer'
s = s.title()
print s
>KröGer

此非 ascii 后面的字母仍为大写。即使我更改字符串:

s = 'KRöger'
s = s.title()
print s
>KröGer

我仍然得到错误的结果。 为什么它会这样?我怎样才能让这个字符串变成“Kröger”?

最佳答案

这应该是 unicode string :

>>> 'KRöger'.title()
'KröGer'
>>> u'KRöGer'.title()
u'Kröger'

编辑:以一个简单的 python 脚本为例:

# -- coding: utf-8 --
print 'KRöger'.title()  # 'KröGer'
print u'KRöGer'.title()  # 'Kröger'
print 'KRöger'.decode('utf-8').title()  # 'Kröger'

关于python - 对具有无效 ASCII 的字符串进行 title() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23503486/

相关文章:

python - 字符串无法粘贴到新的 iPython 5.0

python - 使用 Rietveld Code Review Tool 进行代码审查

python - Pandas 跳过 x 刻度标签

python - "Unexpected EOF"连接到 SQL Server

python - 如何在 Google Colaboratory 中使用 IBM python 模块 "pixiedust"?

python - 从字符串中删除非字母数字但保留编码的非 ASCII 字符 åäö

python - 我想根据某些条件在数据框中添加一列

latex - 如何从 postscript/gnuplot 转换为 pdf 并保留 latex 文档的重音字母?

Python 3.5.2 非 Ascii 字符输出

ruby-on-rails-3.2 - Asciifolding 不工作 Elastic Search Rails