python 字符串string 开头r b u f 含义 str bytes 转换 format

字符串开头r b u f各含义:

b'input\n' # bytes字节符,打印以b开头。
输出:
b'input\n'
r'input\n' # 非转义原生字符,经处理'\n'变成了'\\'和'n'。也就是\n表示的是两个字符,而不是换行。
输出:
'input\\n'
u'input\n' # unicode编码字符,python3默认字符串编码方式。
输出:
'input\n'
import time
t0 = time.time()
time.sleep(1)
name = 'processing'
print(f'{name} done in {time.time() - t0:.2f} s')  # 以f开头表示在字符串内支持大括号内的python 表达式
输出:
processing done in 1.00 s
类似于f开头,大括号变量,:定义格式
coord = (3, 5)
'X: {0[0]};  Y: {0[1]}'.format(coord)

'{0}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'a, b, a'

'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

'{:,}'.format(1234567890)
'1,234,567,890'

'Correct answers: {:.2%}'.format(points/total)
'Correct answers: 86.36%'

str unicode与bytes转换:
python中的encode()和decode()函数

>>> u = '中文'                 # 默认情况下为unicode类型

>>> str1 = u.encode('gb2312')  # 以gb2312编码对u进行编码,获得bytes类型对象
>>> print(str1)
b'\xd6\xd0\xce\xc4'

>>> str2 = u.encode('gbk')     # 以gbk编码对u进行编码,获得bytes类型对象
>>> print(str2)
b'\xd6\xd0\xce\xc4'
>>> str3 = u.encode('utf-8')   # 以utf-8编码对u进行编码,获得bytes类型对象
>>> print(str3)
b'\xe4\xb8\xad\xe6\x96\x87'

>>> u1 = str1.decode('gb2312') # 以gb2312编码对字符串str进行解码,获得字符串类型对象
>>> print('u1')
'中文'

>>> u2 = str1.decode('utf-8')  # 报错,因为str1是gb2312编码的
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd6 in position 0: invalid continuation byte
'€20'.encode('utf-8')
# b'\xe2\x82\xac20'
b'\xe2\x82\xac20'.decode('utf-8')
# '€20'
s1 = '123'
print(s1)
print(type(s1))
s2 = b'123'
print(s2)
print(type(s2))

区别输出:
123
<class 'str'>
b'123'
<class 'bytes'>

Python 2 将字符串处理为 bytes 类型。
Python 3 将字符串处理为 unicode 类型。

str转bytes:
bytes('123', encoding='utf8')
str.encode('123')

bytes转str:
str(b'123', encoding='utf-8')
bytes.decode(b'123')
  • 15
    点赞
  • 55
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值