☰ 目录

Python 字符串

字符串(String)是 Python 中最常用的数据类型,用于表示文本信息。字符串是不可变的字符序列,用单引号 ' '、双引号 " " 或三引号 ''' ''' 包裹。
一、字符串基础操作

操作示例结果
创建s = "Python"Python
长度len(s)6
拼接"Hello" + " " + sHello Python
重复"Hi!" * 3Hi!Hi!Hi!
索引s[0], s[-1]P, n
切片s[2:5], s[::2]tho, Pto

二、字符串转义字符

转义符含义示例输出
\n换行"A\nB"A
B
\t制表符"Name:\tTom"Name: Tom
\\反斜杠"C:\\path"C:\path
\'单引号'It\'s ok'It's ok
\u2605Unicode"Star:\u2605"Star:★

原始字符串(忽略转义):
r"C:\new\folder"C:\new\folder


三、字符串常用方法

1. 大小写转换

"python".upper()      # "PYTHON"
"HELLO".lower()       # "hello"
"title case".title()  # "Title Case"

2. 查找与替换

s = "apple banana apple"
s.find("na")         # 9 (首次出现位置)
s.rfind("apple")     # 12 (末次出现位置)
s.replace("apple", "orange")  # "orange banana orange"

3. 拆分与连接

"a,b,c".split(",")     # ['a', 'b', 'c']
" ".join(["I", "am"])  # "I am"

4. 格式化处理

" python ".strip()        # "python" (去首尾空格)
"center".center(10, "-")  # "--center--"
"ABC".zfill(5)            # "00ABC" (左侧补零)

5. 条件判断

"123".isdigit()   # True (是否全数字)
"abc".isalpha()   # True (是否全字母)
"Python".startswith("Py")  # True
"file.txt".endswith(".txt") # True

四、字符串格式化(三种方式)

1. % 格式化(传统)

name = "Alice"
age = 25
"Name: %s, Age: %d" % (name, age)  # "Name: Alice, Age: 25"

2. str.format()(推荐)

"{} + {} = {}".format(2, 3, 5)          # "2 + 3 = 5"
"{1} before {0}".format("B", "A")       # "A before B"
"{:.2f}%".format(95.1234)               # "95.12%" (保留两位小数)

3. f-string(Python 3.6+ 最佳)

f"{name} is {age} years old"  # "Alice is 25 years old"
import math
f"π ≈ {math.pi:.4f}"         # "π ≈ 3.1416"

 

五、字符串编码与解码

Python 3 默认使用 UTF-8 编码

# 编码:str → bytes
text = "中文"
b = text.encode("utf-8")  # b'\xe4\xb8\xad\xe6\x96\x87'

# 解码:bytes → str
b.decode("utf-8")         # "中文"

六、多行字符串与文档字符串

# 三引号创建多行字符串
poem = """Roses are red,
Violets are blue,
Sugar is sweet,
And so are you."""

# 文档字符串(Docstring)
def add(a, b):
    """计算两数之和
    
    Args:
        a (int): 第一个数
        b (int): 第二个数
    
    Returns:
        int: 两数之和
    """
    return a + b

七、字符串不可变性

s = "Python"
s[0] = "J"  # 报错!TypeError(不可修改)

# 正确做法:创建新字符串
new_s = "J" + s[1:]  # "Jython"

八、字符串驻留机制

Python 会缓存短字符串(通常 ≤ 20 字符),优化内存

a = "hello"
b = "hello"
a is b  # True(相同内存地址)

c = "hello world!"
d = "hello world!"
c is d  # False(长字符串不驻留)

 

九、字符与 Unicode

ord("A")   # 65(字符→Unicode码)
chr(20320) # "你"(Unicode码→字符)

# 遍历字符串
for char in "你好":
    print(char, ord(char))
# 输出:你 20320,好 22909

最佳实践

  1. 优先使用 f-string:简洁高效

  2. 处理路径用原始字符串r"C:\data"

  3. 敏感操作注意编码:如文件读写时指定 encoding='utf-8'

  4. 避免重复拼接:用 join() 代替 + 连接大量字符串

# 低效
result = ""
for s in list_of_strings:
    result += s

# 高效
result = "".join(list_of_strings)

    5.使用 in 关键字检查子串

if "key" in "keyword":  # True

 

 

 

 

 

 

 

 

 

意见反馈

AI助手

代码编辑器