在Python中将某些字符串(utf-8或其他格式)转换为简单ASCII字符串的可靠方法是什么? [英] What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
问题描述
在我的python脚本中,我从一个我未编写的函数中得到了一些字符串.它的编码有所不同.我需要将其转换为ascii格式.有一些万无一失的方法吗?我不介意用空格或其他内容替换非ascii字符...
如果您想要一个ASCII字符串来明确表示您所拥有的内容,而不会丢失任何信息,答案很简单:>
不要编码/解码,请使用 repr()
函数(Python 2.X)或 ascii()
函数(Python 3.x) ).
Inside my python scrip, I get some string back from a function which I didn't write. The encoding of it varies. I need to convert it to ascii format. Is there some fool-proof way of doing this? I don't mind replacing the non-ascii chars with blanks or something else...
If you want an ASCII string that unambiguously represents what you have got, without losing any information, the answer is simple:
Don't muck about with encode/decode, use the repr()
function (Python 2.X) or the ascii()
function (Python 3.x).
这篇关于在Python中将某些字符串(utf-8或其他格式)转换为简单ASCII字符串的可靠方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!