python 内置函数

python ascii()函数用于将对象转化字符串,字符串中ascii字符保持不变(原样输出),对于非ascii字符使用反斜杠“\”形式表示的unicode编码。它是python的内置函数。

语法

语法如下:
ascii(object)

    参数

    • object:要转为ascii字符串的对象

    返回值

    返回ascii类型的字符串。

    程序示例

    #!/usr/bin/python
    # coding=utf-8
    class Student:
        name=""
        def __init__(self,name):
            self.name = name
    
    class Teacher:
        name = ""
        def __init__(self,name):
            self.name = name
    
        def __repr__(self):
            return self.name  
    # 字符串、元组、列表类型
    print('英文字符串:', ascii('yxjc123'))  # 原样输出
    print('中文字符串:', ascii('易学教程123'))  #123原样输出中文转为unicode
    print('list类型的对象:', ascii(['百度','sohu','yxjc123','taobao'])) # list类型 
    print('元组类型的对象:', ascii((1,2,3,4))) # 元组类型
    
    # 对象类型
    S = Student("张三")
    print(ascii(S))
    T = Teacher("李四")
    print(ascii(T)) 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    程序运行结果:

    英文字符串: 'yxjc123'
    中文字符串: '\u6613\u5b66\u6559\u7a0b123'
    list类型的对象: ['\u767e\u5ea6', 'sohu', 'yxjc123', 'taobao']
    元组类型的对象: (1, 2, 3, 4)
    <__main__.Student object at 0x7fb951a76828>
    \u674e\u56db

    对于对象类型的ascii结果中,定义了__repr__()方法 那么ascii输出的结果中就是__repr__方法的内容,否则为对象本身。