首页Python【Python内置函数】a...

【Python内置函数】ascii()函数

Python 提供了许多内置函数,这些函数是Python语言的一部分,可以直接在Python程序中使用而无需导入任何模块。

本系列将会陆续整理分享一些的Python内置函数。

文章配套代码获取有以下两种途径:
  • 通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj 提取码:mnsj
  • 前往GitHub获取
https://github.com/returu/Python_built-in_functions





01
简介

ascii() 函数用于返回对象的可打印表示形式,类似于repr()函数,但不同之处在于ascii()会使用xuU来表示非ASCII字符。

ascii() 函数的基本语法如下:

ascii(object)
参数说明:
  • object:要转换的对象。

返回值:

ascii() 函数返回一个字符串,表示对象的可打印表示形式,其中非ASCII字符会被转换为对应的Unicode编码表示形式。

02
使用

下面是一些使用 ascii() 函数的示例:

# 单个字符
print(ascii('A'))
# 输出: 'A'
print(ascii('©'))
# 输出: 'xa9'

# 字符串
print(ascii('hello'))
# 输出: 'hello'
print(ascii('你好'))
# 输出: 'u4f60u597d'

# 列表
print(ascii([1, 2, 3]))
# 输出: '[1, 2, 3]'

# 字典
print(ascii({'a': 1, 'b': 2}))
# 输出: "{'a': 1, 'b': 2}"

# 自定义对象
class MyClass:
    def __repr__(self):
        return"自定义类:MyClass()"

print(ascii(MyClass()))
# 输出: 'u81eau5b9au4e49u7c7buff1aMyClass()'


本篇文章来源于微信公众号: 码农设计师

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments