python3 ascii_Python ascii()

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()是一个内置函数,并带有一个参数。 此参数可以是任何原始数据类型或对象。 我们还可以将listdicttuple作为参数传递。 在这些情况下,将对集合的元素调用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()函数的快速指南。

GitHub Repository. GitHub存储库中检出完整的python脚本和更多Python示例。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/22644/python-ascii

python3 ascii

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值