Python3 字符串
字符串的创建与访问、转义字符、运算符、格式化、三引号与内建方法。
字符串的创建
Strings can be created with single, double or triple quotes — all equivalent. Adjacent literals concatenate automatically. Strings are immutable: every "modification" returns a new object.
a = 'hello'
b = "hello"
c = """hello"""
d = "py" "thon" # 相邻字面量自动拼接
print(a == b == c, d)
print(type(a), len(a))True python
<class 'str'> 5访问字符串中的值
There is no separate char type: a character is just a string of length 1. Index for one character, slice for a substring — [start:stop:step] includes start, excludes stop, and always copies.
s = "BackendWiki"
print(s[0], s[-1]) # 首字符、末字符
print(s[0:7]) # 前 7 个字符
print(s[7:]) # 从第 7 位到末尾
print(s[::-1]) # 反转
print(s[::2]) # 步长 2B i
Backend
Wiki
ikiWdnekcaB
Bcedii"abc"[1:99] just returns "bc".Python 字符串更新
Strings are immutable, so s[0] = 'b' fails. "Updating" means slicing and concatenating, or using methods like replace/join that return a new string.
s = "Hello, World!"
# s[0] = "h" # TypeError
s2 = "h" + s[1:] # 拼接出「新串」
print(s2)
print(s.replace("World", "Python"))
print("-".join(["a", "b", "c"]))hello, World!
Hello, Python!
a-b-cPython 转义字符
A backslash plus a letter encodes invisible or special characters. For paths and regexes use a raw string r"..." so backslashes stay literal.
| 转义 | 含义 | 示例结果 |
|---|---|---|
| \n | Newline | next line |
| \t | Tab | alignment |
| \\ | Backslash | \ |
| \' | Single quote | ' |
| \" | Double quote | " |
| \r | Carriage return | back to line start |
| \0 | Null | \x00 |
print("第一行\n第二行")
print("姓名\t年龄")
print("路径:C:\\Users\\admin")
print(r"原始字符串:C:\Users\admin") # r 前缀,反斜杠不转义
print(len("\t"), len(r"\t"))第一行
第二行
姓名 年龄
路径:C:\Users\admin
原始字符串:C:\Users\admin
1 2Python 字符串运算符
+ concatenates, * repeats, [] indexes, [:] slices, in tests membership. + only accepts two strings — convert numbers explicitly.
| 运算符 | 作用 | 示例 | 结果 |
|---|---|---|---|
| + | Concatenate | "py" + "thon" | python |
| * | Repeat | "ab" * 3 | ababab |
| [] | Index | "abc"[1] | b |
| [:] | Slice | "abcde"[1:3] | bc |
| in | Membership | "th" in "python" | True |
| not in | Not a member | "z" not in "abc" | True |
a, b = "py", "thon"
print(a + b, b * 2)
print("python"[2], "python"[1:4])
print("th" in "python", "z" in "python")
# print("age: " + 18) # TypeError
print("age: " + str(18))python thonthon
t yth
True False
age: 18Python 字符串格式化
Three generations coexist: % (legacy), str.format() (since 3.0), and f-strings (3.6+, recommended — fastest and most readable).
name, score = "Ada", 0.9234
print("name=%s score=%.2f" % (name, score)) # % 格式化
print("name={} score={:.2f}".format(name, score)) # format
print(f"name={name} score={score:.2%}") # f-stringname=Ada score=0.92
name=Ada score=0.92
name=Ada score=92.34%常用格式说明符
| 写法 | 含义 | 示例 |
|---|---|---|
| {:.2f} | 2 decimals | 3.14159 → 3.14 |
| {:d} | Integer | 42 → 42 |
| {:,} | Thousands separator | 1234567 → 1,234,567 |
| {:>8} | Right align, width 8 | 'ab' → ' ab' |
| {:<8} | Left align, width 8 | 'ab' → 'ab ' |
| {:08.2f} | Zero padding | 42 → 00042.00 |
| {:.1%} | Percent | 0.9234 → 92.3% |
Python 三引号
Triple quotes span lines and preserve newlines — ideal for multi-line text, SQL and HTML. As the first statement in a function or class they become the docstring.
sql = """
SELECT id, name
FROM users
WHERE age > 18
"""
def area(w, h):
"""返回矩形面积。"""
return w * h
print(sql.strip().splitlines()[0])
print(area.__doc__)SELECT id, name
返回矩形面积。f-string 详解
f-strings evaluate expressions inside braces — function calls, arithmetic, nested quotes. A trailing = prints the expression and its value.
user = {"name": "alice", "age": 30}
items = ["a", "b"]
print(f"{user['name']} is {user['age']}")
print(f"{len(items)} items: {', '.join(items)}")
print(f"{user['age'] > 18 = }")
print(f"{2 ** 10 = :,}")alice is 30
2 items: a, b
user['age'] > 18 = True
2 ** 10 = 1,024Unicode 与编码
str is Unicode text, bytes is raw data. Convert at boundaries (file, network, database) and always name the codec.
text = "后端"
raw = text.encode("utf-8")
print(raw)
print(len(text), len(raw))
print(raw.decode("utf-8"))b'\xe5\x90\x8e\xe7\xab\xaf'
2 6
后端Python 字符串内建函数
The table below covers the methods you will actually use. All of them return a new string — the original never changes.
| 方法 | 作用 | 示例 | 结果 |
|---|---|---|---|
| strip() | Trim whitespace | " hi ".strip() | 'hi' |
| split(sep) | Split | "a,b".split(",") | ['a', 'b'] |
| join(iter) | Join | "-".join(["a","b"]) | 'a-b' |
| replace(a,b) | Replace | "aa".replace("a","b") | 'bb' |
| find(x) | Find, -1 if absent | "abc".find("z") | -1 |
| startswith(x) | Prefix test | "api.py".startswith("api") | True |
| upper()/lower() | Case | "ab".upper() | 'AB' |
| zfill(n) | Zero padding | "7".zfill(3) | '007' |
| count(x) | Count | "aba".count("a") | 2 |
| isalnum() | Alphanumeric? | "a1".isalnum() | True |
line = " alice , 30 , admin "
name, age, role = [f.strip() for f in line.split(",")]
print(name, age, role)
print(",".join([name, age, role]))
print("7".zfill(3), "aba".count("a"))alice 30 admin
alice,30,admin
007 2find returns -1 when absent; index raises ValueError. For an existence check, in reads better.字符串的创建
字符串可以用单引号、双引号或三引号创建,三者等价;相邻的两个字符串字面量会自动拼接。字符串是不可变的,任何「修改」操作实际都返回一个新字符串。
a = 'hello'
b = "hello"
c = """hello"""
d = "py" "thon" # 相邻字面量自动拼接
print(a == b == c, d)
print(type(a), len(a))True python
<class 'str'> 5访问字符串中的值
Python 不像 C 那样有单独的字符类型,单个字符就是一个长度为 1 的字符串。用下标访问单个字符,用切片取子串 —— 切片 [start:stop:step] 含头不含尾,且总是返回新字符串。
s = "BackendWiki"
print(s[0], s[-1]) # 首字符、末字符
print(s[0:7]) # 前 7 个字符
print(s[7:]) # 从第 7 位到末尾
print(s[::-1]) # 反转
print(s[::2]) # 步长 2B i
Backend
Wiki
ikiWdnekcaB
Bcedii"abc"[1:99] 得到 "bc"。Python 字符串更新
字符串不可变,所以 s[0] = 'b' 会直接报错。要「更新」只能切片拼接或整体重新赋值,日常更常用 replace、join、format 这类返回新串的方法。
s = "Hello, World!"
# s[0] = "h" # TypeError
s2 = "h" + s[1:] # 拼接出「新串」
print(s2)
print(s.replace("World", "Python"))
print("-".join(["a", "b", "c"]))hello, World!
Hello, Python!
a-b-cPython 转义字符
反斜杠加字母表示不可见字符或特殊符号。写路径、正则时建议用原始字符串 r"...",让反斜杠不再转义。
| 转义 | 含义 | 示例结果 |
|---|---|---|
| \n | 换行 | 下一行 |
| \t | 制表符 | 对齐 |
| \\ | 反斜杠本身 | \ |
| \' | 单引号 | ' |
| \" | 双引号 | " |
| \r | 回车 | 回到行首 |
| \0 | 空字符 | \x00 |
print("第一行\n第二行")
print("姓名\t年龄")
print("路径:C:\\Users\\admin")
print(r"原始字符串:C:\Users\admin") # r 前缀,反斜杠不转义
print(len("\t"), len(r"\t"))第一行
第二行
姓名 年龄
路径:C:\Users\admin
原始字符串:C:\Users\admin
1 2Python 字符串运算符
+ 拼接、* 重复、[] 取字符、[:] 切片、in 判断子串 —— 这些是最常用的五个。注意 + 只接受两个字符串,和数字相加要显式转换。
| 运算符 | 作用 | 示例 | 结果 |
|---|---|---|---|
| + | 拼接 | "py" + "thon" | python |
| * | 重复 | "ab" * 3 | ababab |
| [] | 取字符 | "abc"[1] | b |
| [:] | 切片 | "abcde"[1:3] | bc |
| in | 子串判断 | "th" in "python" | True |
| not in | 不在其中 | "z" not in "abc" | True |
a, b = "py", "thon"
print(a + b, b * 2)
print("python"[2], "python"[1:4])
print("th" in "python", "z" in "python")
# print("age: " + 18) # TypeError
print("age: " + str(18))python thonthon
t yth
True False
age: 18Python 字符串格式化
三代格式化方式并存:% 运算符(老代码常见)、str.format()(3.0 起)、f-string(3.6 起,推荐)。新代码一律用 f-string,它最快也最好读。
name, score = "Ada", 0.9234
print("name=%s score=%.2f" % (name, score)) # % 格式化
print("name={} score={:.2f}".format(name, score)) # format
print(f"name={name} score={score:.2%}") # f-stringname=Ada score=0.92
name=Ada score=0.92
name=Ada score=92.34%常用格式说明符
| 写法 | 含义 | 示例 |
|---|---|---|
| {:.2f} | 保留 2 位小数 | 3.14159 → 3.14 |
| {:d} | 整数 | 42 → 42 |
| {:,} | 千分位 | 1234567 → 1,234,567 |
| {:>8} | 右对齐宽度 8 | 'ab' → ' ab' |
| {:<8} | 左对齐宽度 8 | 'ab' → 'ab ' |
| {:08.2f} | 补零 | 42 → 00042.00 |
| {:.1%} | 百分比 | 0.9234 → 92.3% |
Python 三引号
三个引号可以跨行,里面的换行会原样保留,所以适合写多行文本、SQL、HTML 片段。放在函数或类的第一行时,它还会变成文档字符串(docstring)。
sql = """
SELECT id, name
FROM users
WHERE age > 18
"""
def area(w, h):
"""返回矩形面积。"""
return w * h
print(sql.strip().splitlines()[0])
print(area.__doc__)SELECT id, name
返回矩形面积。f-string 详解
f-string 在花括号里直接求值,可以调用函数、做运算、嵌套引号;= 结尾是调试神器,会同时打印表达式和结果。
user = {"name": "alice", "age": 30}
items = ["a", "b"]
print(f"{user['name']} is {user['age']}")
print(f"{len(items)} items: {', '.join(items)}")
print(f"{user['age'] > 18 = }")
print(f"{2 ** 10 = :,}")alice is 30
2 items: a, b
user['age'] > 18 = True
2 ** 10 = 1,024Unicode 与编码
Python 3 的 str 是 Unicode 文本,bytes 是字节序列。二者在边界处(文件、网络、数据库)转换,转换时必须显式指定编码。
text = "后端"
raw = text.encode("utf-8")
print(raw)
print(len(text), len(raw))
print(raw.decode("utf-8"))b'\xe5\x90\x8e\xe7\xab\xaf'
2 6
后端Python 字符串内建函数
下表是日常使用频率最高的方法。记住一点:所有方法都返回新字符串,原串不变。
| 方法 | 作用 | 示例 | 结果 |
|---|---|---|---|
| strip() | 去两端空白 | " hi ".strip() | 'hi' |
| split(sep) | 按分隔符切分 | "a,b".split(",") | ['a', 'b'] |
| join(iter) | 拼接 | "-".join(["a","b"]) | 'a-b' |
| replace(a,b) | 替换 | "aa".replace("a","b") | 'bb' |
| find(x) | 查找,缺失返回 -1 | "abc".find("z") | -1 |
| startswith(x) | 前缀判断 | "api.py".startswith("api") | True |
| upper()/lower() | 大小写 | "ab".upper() | 'AB' |
| zfill(n) | 左侧补零 | "7".zfill(3) | '007' |
| count(x) | 计数 | "aba".count("a") | 2 |
| isalnum() | 是否全为字母数字 | "a1".isalnum() | True |
line = " alice , 30 , admin "
name, age, role = [f.strip() for f in line.split(",")]
print(name, age, role)
print(",".join([name, age, role]))
print("7".zfill(3), "aba".count("a"))alice 30 admin
alice,30,admin
007 2find 找不到返回 -1,index 找不到直接抛 ValueError。要判断「在不在」,用 in 更清楚。