python - 删除扩展 Ascii 并保留文本

标签 python string ascii

如何隐藏包含扩展 ascii 的字符串来表示数字的幂,同时保留指数值?例如,如果字符串是“m\xb3/h”,旨在表示每小时的立方米,我想返回字符串“m3/h”。或者“m\xb2”应该返回“m2”。

代码-

varUnit = 'm\xb3/h'
varUnit.decode('ascii', 'ignore').endcode('ascii')
print varUnit

返回“m/h”,而需要“m3/h”。

最佳答案

嗯,首先要知道的是,不存在“扩展 ascii”。 Ascii 已经以多种不同的方式进行了扩展。快速测试表明您需要“latin_1”或“cp1252”。因此,首先将其转换为 unicode(一种存储任何字符的方式):

varUnit = varUnit.decode("latin_1")

编辑:如果您只想在自己的应用程序中显示它,您应该停在这里并使用 Unicode。 print varUnit 应该为您提供 。但遗留系统可能无法处理它,在这种情况下:

然后,您需要将其简化为可以用纯 ASCII 表示的字符。最简单的方法是使用 unidecode 模块(您可以使用 pip 或 easy_install 安装它):

from unidecode import unidecode
print unidecode(varUnit)

关于python - 删除扩展 Ascii 并保留文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4715108/

相关文章:

java - 如何从左到右跟踪和移动字符串?

c++ - `const char*' 到 `char'

sql - 将 ASCII(子)集传输到表

C - char 和 int 之间的 acsii 转换

python - 使用 NDB 中的 Key 检索实体

c# - .NET 字符串性能问题

python - 给定纬度/经度,说明坐标是否在美国大陆内

c++ - 将整数转换为 ascii 值 C++

python - python 中检查括号是否平衡的函数

python - Pip 不适用于 Ubuntu 上的 Python 3.10