Python学习之常用函数
发布日期:2022-02-26 14:49:30 浏览次数:38 分类:技术文章

本文共 971 字,大约阅读时间需要 3 分钟。

字符

对于单个字符的编码,Python提供了ord()函数把字符转换为字符的编码数,chr()函数把编码转换为对应的字符:

>>> ord('A')  65  >>> ord('中')  20013  >>> chr(66)  'B'  >>> chr(25991)  '文'
以Unicode表示的str通过encode()方法可以编码为指定的bytes,例如:(' '.encode(' '))

>>> 'ABC'.encode('ascii')  b'ABC'  >>> '中文'.encode('utf-8')  b'\xe4\xb8\xad\xe6\x96\x87'  >>> '中文'.encode('ascii')  >>> x='ABC'  >>> x.encode('utf-8')  b'ABC'
反过来,如果我们从网络或磁盘上读取了字节流,那么读到的数据就是bytes。要把bytes变为str,就需要用decode()方法:(' '.decode(' '))

>>> b'ABC'.decode('ascii')  'ABC'  >>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')  '中文'

len()
要计算str包含多少个字符,可以用len()函数,同样可以计算list包含元素个数:
>>>s=[1,2,3]>>>len(s)3
>>> len('ABC')  3  >>> len('中文')  2
len()函数计算的是str的字符数,如果换成bytes,len()函数就计算字节数:
>>> len(b'ABC')  3  >>> len(b'\xe4\xb8\xad\xe6\x96\x87')  6  >>> len('中文'.encode('utf-8'))  6
print格式化
>>> print('%2d-%02d' % (3, 1))  3-01  >>> print('%.2f' % 3.1415926)  3.14>>> 'Age: %s. Gender: %s' % (25, True)  'Age: 25. Gender: True' >>> 'growth rate: %d %%' % 7  'growth rate: 7 %'

转载地址:https://blog.csdn.net/qq_31335867/article/details/79086497 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:簡單的流式佈局
下一篇:angularjs表单

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年03月22日 10时11分32秒