python3 ascii
Python ascii() function returns the string representation of the object. This function internally calls repr() function and before returning the representation string, escapes the non-ASCII characters using \x, \u or \U escapes.
Python ascii()函数返回对象的字符串表示形式。 此函数在内部调用repr()函数,并在返回表示形式的字符串之前,使用\ x,\ u或\ U转义符对非ASCII字符进行转义。
Python ascii() (Python ascii())
Python ascii() is a built-in function and takes a single argument. This argument can be any primitive data type or object. We can also pass list, dict or tuple as an argument. In these cases, the ascii() method will be called on the elements of the collection and string representation is returned.
Python ascii()是一个内置函数,并带有一个参数。 此参数可以是任何原始数据类型或对象。 我们还可以将list , dict或tuple作为参数传递。 在这些情况下,将对集合的元素调用ascii()方法,并返回字符串表示形式。
带有数字,布尔值,字符串的Python ascii()示例 (Python ascii() example with number, boolean, string)
s = 5 #numbers
print(ascii(s))
s = True # boolean
print(ascii(s))
# strings
s = 'abc'
print(ascii(s))
s = 'èvõłvé'
print(ascii(s))
Output:
输出:
5
True
'abc'
'\xe8v\xf5\u0142v\xe9'
带有列表,元组和字典的Python ascii()示例 (Python ascii() example with list, tuple and dict)
l = ['æ', 'b', 'č']
print(ascii(l))
t = (1, 'æ', 'b', 'č', 5)
print(ascii(t))
d = {'â':'å', '2':2, 'ç':'ć'}
print(ascii(d))
Output:
输出:
['\xe6', 'b', '\u010d']
(1, '\xe6', 'b', '\u010d', 5)
{'\xe2': '\xe5', '2': 2, '\xe7': '\u0107'}
带有自定义对象的Python ascii() (Python ascii() with custom object)
Let’s say we have a class defined as:
假设我们有一个定义为的类:
class Employee:
name = ""
def __init__(self, n):
self.name = n
Now if we have the following code snippet:
现在,如果我们有以下代码片段:
e = Employee('Pànkáj')
print(ascii(e))
Output:
输出:
<__main__.Employee object at 0x1061e2d68>
Since we didn’t defined repr() function, Object class repr() definition is used. If we want to use ascii() for any object, we should define its repr() function.
由于我们没有定义repr()函数,因此使用对象类repr()定义。 如果要对任何对象使用ascii(),则应定义其repr()函数。
Let’s add below function to Employee class.
让我们将以下函数添加到Employee类。
def __repr__(self):
return self.name
Now the output of above snippet will be:
现在以上代码段的输出将是:
P\xe0nk\xe1j
That’s all for a quick guide on python ascii() function.
这就是python ascii()函数的快速指南。
Reference: Official Documentation
参考: 官方文档
python3 ascii