Python的str() repr() ascii()的用法

Python的str() repr() ascii()的用法

str() 函数将对象转化为适于人阅读的形式。
repr() 函数将对象转化为供解释器读取的形式。
ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串, 但是对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 x, u 或 U 编码的字符。 生成字符串类似 Python2 版本中 repr() 函数的返回值。

接下来用实例对比一下这三个函数:

number = (3+4j)
print(type(number))
# 输出: 
# <class 'complex'>

print(str(number))
print(type(str(number)))
# 输出: 
# (3+4j)
# <class 'str'>

print(repr(number))
print(type(repr(number)))
# 输出: 
# (3+4j)
# <class 'str'>

print(ascii(number))
print(type(ascii(number)))
# 输出: 
# (3+4j)
# <class 'str'>

三个函数均是将对象转化成字符串形式。
这个例子没有看出来区别。
接下来再将字符串对象作为参数:

string = 'Hello World'
print(str(string))
print(type(str(string)))
# 输出:
# Hello World
# <class 'str'>

string = 'Hello World'
print(repr(string))
print(type(repr(string)))
# 输出:
# 'Hello World'
# <class 'str'>

string = 'Hello World'
print(ascii(string))
print(type(ascii(string)))
# 输出:
# 'Hello World'
# <class 'str'>

str() 函数运行结果是 Hello World ,是适于人阅读的形式。
repr() 函数运行结果是 ‘Hello World’ ,是供解释器读取的形式。
ascii() 函数类似 repr() 函数,
那么ascill() 函数不同在哪呢?

string = '中文'
print(str(string))
print(type(str(string)))
# 输出:
# 中文
# <class 'str'>

string = '中文'
print(repr(string))
print(type(repr(string)))
# 输出:
# '中文'
# <class 'str'>

string = '中文'
print(ascii(string))
print(type(ascii(string)))
# 输出:
# 'u4e2du6587'
# <class 'str'>

ascii() 函数对于字符串中的非 ASCII 字符则返回通过 repr() 函数使用 x(十六进制形式), u 或 U(unicode 码) 编码的字符。 生成字符串类似 Python2 版本中 repr() 函数的返回值。

  1. ASCII (American Standard Code for Information Interchange)
    计算机刚出现时设计的编码,只包含英文字符

  2. 非ASCII
    随着计算机的普及,计算机必须要支持其他国家的语言,但ASCII只支持英文字符,所以只能新增其他的字符集,如汉字的GB2312、BIG5。

  3. Unicode
    每个国家都有自己的字符集易导致混乱不统一,比如A文件在B国家是正常的,但是到C国家就显示乱码。所以就出现了Unicode,称为统一码、万国码,它包含了所有的字符,它为每种语言的每个字符都定了统一的、唯一的二进制编号,用以满足跨语言,跨平台的需求。

  4. UTF-8 (Unicode Transformation Format 8-bit)
    a、由于Unicode字符集太大,里面很多字符在某些国家基本不会用到,且Unicode储存字符时需要至少2个字节以上的空间,很浪费资源。如A字符在ASCII中只占1个字节,但在Unicode最少占2个字节。所以就出现了UTF-8,UTF-8是Unicode的一种实现方式(UTF-8全称 在UTF-8编码中原本只需要一个字节的ASCII字符,仍然只占一个字节,而复杂字符就需要2个到6个字节来存储。
    b、由于Unicode只规定了编码方式,未规定解码方式。如有一串2字节的二进制,是以1个字节为1个字符的方式解码还是2个字节为1个字符的方式。出现UTF-8编码后就可以用UTF-8的方式来解析这串二进制。

原文地址:https://www.cnblogs.com/jiaohuadehulike/p/14295018.html