str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr

目录

str()     repr()

format()

bytes()    bytearry()    memoryview()

ord()    chr()    ascii()


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'"

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值