Python 中的字符串可以从三个方面理解:
- 使用什么引号
- 字符串前面的
f、r、b等前缀 - 如何把变量格式化到字符串中
1. 普通字符串
单引号和双引号都可以表示字符串,功能没有区别。
python
name1 = 'Bob'
name2 = "Bob"
可以根据字符串内容选择更方便的引号:
python
text1 = "I'm Bob"
text2 = '他说:"你好"'
如果内外使用相同的引号,需要通过 \ 转义:
python
text = 'I\'m Bob'
print(text)
输出:
text
I'm Bob
2. 多行字符串
三个单引号或三个双引号可以表示多行字符串:
python
text = """
第一行
第二行
第三行
"""
print(text)
多行字符串经常用于:
- 多行文本
- SQL 语句
- HTML 内容
- 函数、类和模块的文档字符串
例如:
python
def add(a, b):
"""返回两个数字的和。"""
return a + b
3. f-string
字符串前面的 f 表示格式化字符串。
变量或者表达式可以写在 {} 中:
python
name = 'Bob'
age = 18
text = f'姓名:{name},年龄:{age}'
print(text)
输出:
text
姓名:Bob,年龄:18
花括号中也可以编写表达式:
python
a = 10
b = 20
print(f'{a} + {b} = {a + b}')
输出:
text
10 + 20 = 30
还可以调用方法:
python
name = 'bob'
print(f'姓名:{name.upper()}')
输出:
text
姓名:BOB
3.1 保留小数位数
python
price = 12.3456
print(f'价格:{price:.2f}')
输出:
text
价格:12.35
其中:
f表示按照浮点数格式显示.2表示保留两位小数
3.2 千位分隔符
python
money = 1234567
print(f'{money:,}')
输出:
text
1,234,567
3.3 百分比
python
rate = 0.856
print(f'{rate:.1%}')
输出:
text
85.6%
3.4 数字补零
python
number = 7
print(f'{number:03d}')
输出:
text
007
其中:
d表示十进制整数3表示总宽度为 30表示空余位置用0填充
3.5 字符串对齐
python
name = 'Bob'
print(f'|{name:<10}|') # 左对齐
print(f'|{name:^10}|') # 居中
print(f'|{name:>10}|') # 右对齐
输出:
text
|Bob |
| Bob |
| Bob|
格式说明:
| 格式 | 含义 |
|---|---|
<10 |
占用 10 个字符宽度并左对齐 |
^10 |
占用 10 个字符宽度并居中 |
>10 |
占用 10 个字符宽度并右对齐 |
Bob 长度为 3,指定宽度为 10,因此还需要填充 7 个空格。
也可以指定填充字符:
python
name = 'Bob'
print(f'|{name:-<10}|') # 使用 - 填充并左对齐
print(f'|{name:-^10}|') # 使用 - 填充并居中
print(f'|{name:->10}|') # 使用 - 填充并右对齐
输出:
text
|Bob-------|
|---Bob----|
|-------Bob|
格式结构为:
text
{变量:填充字符 对齐方式 宽度}
例如:
python
{name:-^10}
表示:
-:使用短横线填充^:居中10:总宽度为 10
还可以用来制作简单的表格:
python
print(f'{"姓名":<10}{"年龄":>5}')
print(f'{"Bob":<10}{18:>5}')
print(f'{"Alice":<10}{20:>5}')
输出:
text
姓名 年龄
Bob 18
Alice 20
注意:中文字符在某些终端中可能占两个显示宽度,因此中文表格的视觉对齐可能受到终端影响。
3.6 显示花括号
在 f-string 中,花括号具有特殊含义:
python
name = 'Bob'
print(f'{name}')
输出:
text
Bob
如果想显示真正的 { 和 },需要写两个花括号:
python
print(f'{{name}}')
输出:
text
{name}
4. 原始字符串 r
字符串前面的 r 表示原始字符串,即 raw string。
普通字符串会处理转义字符:
python
text = 'hello\nworld'
print(text)
输出:
text
hello
world
使用原始字符串后:
python
text = r'hello\nworld'
print(text)
输出:
text
hello\nworld
原始字符串常用于正则表达式:
python
import re
pattern = r'\d+\.\d+'
也常用于 Windows 路径:
python
path = r'C:\Users\Bob\Desktop'
原始字符串不能以单个反斜杠结尾:
python
# 错误写法
path = r'C:\Users\'
5. 字节串 b
字符串前面的 b 表示字节串:
python
data = b'Hello'
字节串的类型是 bytes,不是 str:
python
print(type('Hello'))
print(type(b'Hello'))
输出:
text
<class 'str'>
<class 'bytes'>
str 表示文本,bytes 表示二进制数据。
字符串转换成字节:
python
text = '你好'
data = text.encode('utf-8')
print(data)
字节转换回字符串:
python
text = data.decode('utf-8')
print(text)
字节串常用于:
- 网络通信
- 二进制文件
- 图片和音频
- 加密和哈希计算
6. Unicode 字符串 u
python
text = u'你好'
在 Python 3 中,普通字符串默认就是 Unicode,因此下面两种写法基本相同:
python
text1 = u'你好'
text2 = '你好'
u 前缀主要用于兼容旧代码。
7. 字符串前缀组合
7.1 fr 或 rf
f 和 r 可以组合:
python
name = 'Bob'
path = rf'C:\Users\{name}\Desktop'
print(path)
输出:
text
C:\Users\Bob\Desktop
其中:
f负责解析{name}r让反斜杠保持原样
它也适合生成动态正则表达式:
python
word = 'hello'
pattern = rf'\b{word}\b'
print(pattern)
输出:
text
\bhello\b
7.2 br 或 rb
字节串和原始字符串也可以组合:
python
data1 = br'\n'
data2 = rb'\n'
print(data1)
print(data2)
输出:
text
b'\\n'
b'\\n'
这里的 \n 是字面量,而不是换行符。
8. 常见转义字符
| 写法 | 含义 |
|---|---|
\n |
换行 |
\r |
回车 |
\r\n |
Windows 换行 |
\t |
制表符 |
\\ |
一个反斜杠 |
\' |
单引号 |
\" |
双引号 |
\b |
退格 |
\0 |
空字符 |
\u4f60 |
Unicode 字符 |
例如:
python
print('姓名:Bob\n年龄:18')
输出:
text
姓名:Bob
年龄:18
9. str.format() 格式化
除了 f-string,还可以使用 str.format():
python
name = 'Bob'
age = 18
text = '姓名:{},年龄:{}'.format(name, age)
print(text)
输出:
text
姓名:Bob,年龄:18
也可以指定参数名称:
python
text = '姓名:{name},年龄:{age}'.format(
name='Bob',
age=18
)
print(text)
格式控制:
python
price = 12.3456
print('价格:{:.2f}'.format(price))
输出:
text
价格:12.35
10. % 格式化
这是一种较旧的字符串格式化方式:
python
name = 'Bob'
age = 18
text = '姓名:%s,年龄:%d' % (name, age)
print(text)
输出:
text
姓名:Bob,年龄:18
常见占位符:
| 占位符 | 含义 |
|---|---|
%s |
字符串 |
%d |
十进制整数 |
%f |
浮点数 |
%.2f |
保留两位小数 |
%x |
十六进制整数 |
例如:
python
price = 12.3456
print('价格:%.2f' % price)
输出:
text
价格:12.35
新代码通常优先使用 f-string:
python
print(f'姓名:{name},年龄:{age}')
11. 常用字符串方法
大小写转换
python
text = 'Hello World'
print(text.lower())
print(text.upper())
print(text.title())
去除两端空白
python
text = ' hello '
print(text.strip())
print(text.lstrip())
print(text.rstrip())
替换内容
python
text = 'Hello Bob'
print(text.replace('Bob', 'Alice'))
输出:
text
Hello Alice
分割字符串
python
text = 'apple,banana,orange'
fruits = text.split(',')
print(fruits)
输出:
text
['apple', 'banana', 'orange']
拼接字符串
python
fruits = ['apple', 'banana', 'orange']
text = ','.join(fruits)
print(text)
输出:
text
apple,banana,orange
判断字符串内容
python
text = 'Hello Python'
print(text.startswith('Hello'))
print(text.endswith('Python'))
print('Python' in text)
输出:
text
True
True
True
12. 总结
常见字符串写法:
python
'hello' # 普通字符串
"hello" # 普通字符串
"""多行字符串""" # 多行字符串
f'hello {name}' # 格式化字符串
r'C:\Users\Bob' # 原始字符串
b'hello' # 字节串
rf'\b{name}\b' # 原始字符串和格式化字符串组合
日常开发中的选择:
| 使用场景 | 推荐写法 |
|---|---|
| 普通文本 | '...' 或 "..." |
| 插入变量 | f'...{变量}...' |
| 正则表达式 | r'...' |
| 二进制数据 | b'...' |
| 动态正则表达式 | rf'...' |
| 多行文本 | '''...''' 或 """...""" |