Python3 字符串

字符串的创建与访问、转义字符、运算符、格式化、三引号与内建方法。

Beginner
Key Points字符串是不可变序列,切片会复制;格式化优先 f-string,编码转换在边界处显式指定 utf-8。

字符串的创建

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.

Python
a = 'hello'
b = "hello"
c = """hello"""
d = "py" "thon"          # 相邻字面量自动拼接

print(a == b == c, d)
print(type(a), len(a))
Output
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.

Python
s = "BackendWiki"

print(s[0], s[-1])        # 首字符、末字符
print(s[0:7])             # 前 7 个字符
print(s[7:])              # 从第 7 位到末尾
print(s[::-1])            # 反转
print(s[::2])             # 步长 2
Output
B i
Backend
Wiki
ikiWdnekcaB
Bcedii
Out-of-range indexing raises IndexError, but slicing never does — "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.

Python
s = "Hello, World!"

# s[0] = "h"                      # TypeError

s2 = "h" + s[1:]                   # 拼接出「新串」
print(s2)

print(s.replace("World", "Python"))
print("-".join(["a", "b", "c"]))
Output
hello, World!
Hello, Python!
a-b-c

Python 转义字符

A backslash plus a letter encodes invisible or special characters. For paths and regexes use a raw string r"..." so backslashes stay literal.

转义含义示例结果
\nNewlinenext line
\tTabalignment
\\Backslash\
\'Single quote'
\"Double quote"
\rCarriage returnback to line start
\0Null\x00
Python
print("第一行\n第二行")
print("姓名\t年龄")
print("路径:C:\\Users\\admin")
print(r"原始字符串:C:\Users\admin")   # r 前缀,反斜杠不转义
print(len("\t"), len(r"\t"))
Output
第一行
第二行
姓名	年龄
路径:C:\Users\admin
原始字符串:C:\Users\admin
1 2

Python 字符串运算符

+ concatenates, * repeats, [] indexes, [:] slices, in tests membership. + only accepts two strings — convert numbers explicitly.

运算符作用示例结果
+Concatenate"py" + "thon"python
*Repeat"ab" * 3ababab
[]Index"abc"[1]b
[:]Slice"abcde"[1:3]bc
inMembership"th" in "python"True
not inNot a member"z" not in "abc"True
Python
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))
Output
python thonthon
t yth
True False
age: 18

Python 字符串格式化

Three generations coexist: % (legacy), str.format() (since 3.0), and f-strings (3.6+, recommended — fastest and most readable).

Python
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-string
Output
name=Ada score=0.92
name=Ada score=0.92
name=Ada score=92.34%

常用格式说明符

写法含义示例
{:.2f}2 decimals3.14159 → 3.14
{:d}Integer42 → 42
{:,}Thousands separator1234567 → 1,234,567
{:>8}Right align, width 8'ab' → ' ab'
{:<8}Left align, width 8'ab' → 'ab '
{:08.2f}Zero padding42 → 00042.00
{:.1%}Percent0.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.

Python
sql = """
SELECT id, name
FROM users
WHERE age > 18
"""

def area(w, h):
    """返回矩形面积。"""
    return w * h

print(sql.strip().splitlines()[0])
print(area.__doc__)
Output
SELECT id, name
返回矩形面积。

f-string 详解

f-strings evaluate expressions inside braces — function calls, arithmetic, nested quotes. A trailing = prints the expression and its value.

Python
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 = :,}")
Output
alice is 30
2 items: a, b
user['age'] > 18 = True
2 ** 10 = 1,024
Before 3.12, backslashes are not allowed inside f-string braces. Never build SQL with f-strings — that is SQL injection.

Unicode 与编码

str is Unicode text, bytes is raw data. Convert at boundaries (file, network, database) and always name the codec.

Python
text = "后端"
raw = text.encode("utf-8")

print(raw)
print(len(text), len(raw))
print(raw.decode("utf-8"))
Output
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
Python
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"))
Output
alice 30 admin
alice,30,admin
007 2
find returns -1 when absent; index raises ValueError. For an existence check, in reads better.

Friends & Partners