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

本文深入探讨了Python中不同类型的字符串,包括bytes、非转义原生字符串和unicode编码字符串的区别及应用。通过实例展示了字符串格式化的方法,以及如何在不同编码间进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串开头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')
### Python字符串类型的转换 #### 将其他类型转换字符串Python 中,可以通过内置函数 `str()` 来实现大多数基本数据类型到字符串转换。这使得程序能够轻松处理不同形式的数据作为文本输出。 ```python number = 12345 string_number = str(number) # 转换整数为字符串 print(string_number, type(string_number)) # 输出: 12345 <class 'str'>[^1] ``` 对于更复杂的数据结构如列表、字典等同样适用: ```python data_dict = {'key': 'value'} string_data = str(data_dict) print(string_data, type(string_data)) # 输出: {'key': 'value'} <class 'str'> ``` #### 使用格式化字符串进行转换 另一种常见的方式是通过格式化字符串来完成这种转变,特别是当希望控制输出格式的时候。Python 支持多种方式来进行字符串插值和格式化,其中 f-string 是一种简洁而强大的工具,在表达式前面加上字母`f`或`F`即可创建一个格式化的字符串文字^[^2]^。 ```python name = "Alice" age = 30 formatted_string = f"My name is {name}, and I am {age} years old." print(formatted_string) # 输出: My name is Alice, and I am 30 years old.[^2] ``` 此外,还可以使用 `.format()` 方法来进行更为灵活复杂的替换操作: ```python template = "Value of pi up to two decimal places: {:.2f}" pi_value = 3.14159 result = template.format(pi_value) print(result) # Value of pi up to two decimal places: 3.14 ``` #### 特殊情况下的编码解码 值得注意的是,在某些情况下可能涉及到 bytes 和 bytearray 类型与字符串之间的相互转化,这时就需要考虑编码问题了。通常会指定 UTF-8 编码方式进行转码工作^[^3]^。 ```python original_str = "Hello world!" encoded_bytes = original_str.encode('utf-8') # 字符串 -> byte[] decoded_str = encoded_bytes.decode('utf-8') # byte[] -> 字符串 print(f"Encoded Bytes: {list(encoded_bytes)}\nDecoded String: {decoded_str}") ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值