目录
bytes() bytearry() memoryview()
str()
函数将对象转化为字符串
format()
一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
基本语法是通过c{} 和 : 来代替以前的 %
"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
"{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
"{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
#左对齐 右对齐 居中
print(format('test', '<20'))
print(format('test', '>40'))
print(format('test', '^40'))
bytes()
函数将对象转化为一个新的不可修改字节数组
print(bytes('你好',encoding='GBK')) # unicode转换成GBK的bytes
print(bytes('你好',encoding='utf-8')) # unicode转换成utf-8的bytes
'''
b'\xc4\xe3\xba\xc3'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
'''
bytearry()
函数将对象转化为一个新的可修改字节数组
ret = bytearray('alex',encoding='utf-8')
print(id(ret))
print(ret[0])
ret[0] = 65
print(ret)
print(id(ret))
'''
bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
228
'''
memoryview()
函数返回给定参数的内存查看对象(Momory view)
利用memoryview精准的修改一个数组的某个字节
ret = memoryview(bytes('你好',encoding='utf-8'))
print(len(ret))
print(bytes(ret[:3]).decode('utf-8'))
print(bytes(ret[3:]).decode('utf-8'))
'''
6
你
好
'''
ord()
函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python 定义范围,则会引发一个 TypeError 的异常
print(ord('a'))
97
print(ord('b'))
98
chr()
用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符
print(chr(0x30), chr(0x31), chr(0x61)) # 十六进制
0 1 a
print(chr(48), chr(49), chr(97)) # 十进制
0 1 a
ascii()
返回一个可打印的对象字符串方式表示,如果是非ascii字符就会输出\x,\u或\U等字符来表示
print(ascii(1))
'1'
print(ascii('&'))
"'&'"
repr()
函数将对象转化为供解释器读取的形式,即以合法python表达式的形式来表示值
s = 'RUNOOB'
print(repr(s))
"'RUNOOB'"