2

我想转换这个字符串

foo_utf = u'nästy chäräctörs with å and co.' # unicode

进入这个

foo_ascii = 'nästy chäräctörs with å and co.' # ASCII

.

知道如何在 Python (2.6) 中执行此操作吗?我找到了unicodedata模块,但我不知道如何进行转换。

4

5 回答 5

4

我不认为你可以。那些“nästy chäräctörs”不能被编码为 ASCII,所以你必须选择不同的编码(UTF-8 或 Latin-1 或 Windows-1252 之类的)。

于 2010-03-25T17:47:03.533 回答
3

试试encode串的方法。

>>> u'nästy chäräctörs with å and co.'.encode('latin-1')
'n\xe4sty ch\xe4r\xe4ct\xf6rs with \xe5 and co.'
于 2010-03-25T17:43:07.863 回答
3

python的stdlib中的模块中有几个选项codecs,具体取决于您希望如何处理扩展字符:

>>> import codecs
>>> u = u'nästy chäräctörs with å and co.'
>>> encode = codecs.get_encoder('ascii')
>>> encode(u) 
'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128)
>>> encode(u, 'ignore')
('nsty chrctrs with  and co.', 31)
>>> encode(u, 'replace')
('n?sty ch?r?ct?rs with ? and co.', 31)
>>> encode(u, 'xmlcharrefreplace')
('n&#228;sty ch&#228;r&#228;ct&#246;rs with &#229; and co.', 31)
>>> encode(u, 'backslashreplace')
('n\\xe4sty ch\\xe4r\\xe4ct\\xf6rs with \\xe5 and co.', 31)

希望其中之一能满足您的需求。Python 编解码器模块文档中提供了更多信息。

于 2010-03-25T18:36:44.237 回答
2

您还可以使用 python 中提供的 unicodedata 模块 ( http://docs.python.org/library/unicodedata.html ) 将大量 unicode 值转换为 Ascii 变体。IE 修复了不同的 "s 等。通过 encode() 方法跟进,您可以完全清理字符串。

您主要从 unicodedata 中提取的方法是规范化并将其传递给 NFKC 标志。

于 2010-03-25T18:30:46.050 回答
2

这确实是一个 Django 问题,而不是一个 python 问题。如果字符串在您的 .py 文件之一中,请确保您的文件顶部有以下行: -*- coding: utf-8 -*-

此外,您的字符串必须是“unicode”(u'foobar')类型

然后确保您的 html 页面在 unicode 中工作:

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

这应该可以解决问题。无需编码/解码等,只需确保一切都是 unicode,并且您是安全的。

于 2010-03-25T19:27:23.503 回答