文档首页> Linux命令> python基础字符串操作

python基础字符串操作

发布时间:2025-07-31 00:08       

Python基础字符串操作指南

字符串是Python中最常用的数据类型之一,掌握其核心操作是编程基础。以下是经过系统梳理的20个关键操作,覆盖日常开发90%的需求:


🔍 一、字符串创建与基础

s1 = "Hello"            # 双引号
s2 = 'Python'           # 单引号
s3 = """多行
字符串"""               # 三引号(保留换行符)
s4 = str(3.14)          # 类型转换 → "3.14"
​

⚙️ 二、核心操作(附高频场景)

1. 索引与切片

s = "Python"
print(s[0])     # 'P'(正向索引从0开始)
print(s[-1])    # 'n'(负索引:-1=最后一个字符)
print(s[2:5])   # 'tho'(切片:[起始:结束:步长])
print(s[::-1])  # 'nohtyP'(逆序技巧)
​

2. 拼接与重复

print("Hi" + "!"*3)     # "Hi!!!"(重复操作符*)
fname = "张"
lname = "三"
full_name = f"{lname}{fname}"  # f-string拼接 → "三张"
​

3. 长度与存在性检测

len("中国")              # 2(中文字符长度=1)
print("Py" in "Python") # True(子串检测)
​

🔧 三、字符串方法(重点掌握)

1. 大小写转换

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

2. 去除空白字符

"  text  ".strip()     # "text"(去首尾空格)
"**word**".strip('*')  # "word"(自定义去除字符)
​

3. 分割与连接

"a,b,c".split(",")     # ['a','b','c'](字符串→列表)
"-".join(['2023','08','15'])  # "2023-08-15"(列表→字符串)
​

4. 查找与替换

"apple".find("p")      # 1(返回首次出现的索引,未找到=-1)
"banana".count("a")    # 3(统计出现次数)
"Hello Java".replace("Java", "Python")  # "Hello Python"
​

5. 格式化输出(3种方式)

# f-string (Python 3.6+推荐)
name = "Li Lei"
print(f"你好, {name}!")
 
# format()方法
"坐标: ({x},{y})".format(x=10, y=20)
 
# %格式化(旧式)
"进度: %d%%" % 75  # → "进度: 75%"
​

🚨 四、中文处理要点

# 中英混合字符串操作
text = "Python中文社区"
print(text[6:8])        # "中文"(正确切片)
print(len("汉字"))       # 2(长度计算准确)
print("社区" in text)   # True(包含检测)
​

💡 五、实用技巧

  1. 字符串反转
    s = "abc"; s_rev = s[::-1] → "cba"
  2. 检查前缀/后缀
    "file.txt".endswith(".txt") → True
    "http://url".startswith("http") → True
  3. 字符类型判断
    "123".isdigit()    # True(纯数字)
    "abc".isalpha()    # True(纯字母)
    "a1b2".isalnum()   # True(字母或数字)
    ​
  4. 填充对齐
    "42".zfill(5)      # "00042"(零填充)
    "hi".center(10, "-") # "----hi----"(居中填充)
    ​

⚠️ 六、避坑指南

  1. 字符串不可变性
    s = "Python"
    s[0] = "J"  # ❌ 报错!需转换为列表修改后再转回
    # 正确做法:
    s_list = list(s)
    s_list[0] = "J"
    s = "".join(s_list)  # "Jython"
    ​
  2. 编码问题
    # 处理文件时指定编码
    with open("data.txt", "r", encoding="utf-8") as f:
        text = f.read()
    ​
  3. 原始字符串(处理路径/正则)
    path = r"C:\new_folder\data"  # r前缀避免转义
    ​

📊 七、性能优化

操作 推荐方式 避免方式
字符串拼接 "".join(list) s1 + s2 + s3
循环内修改 先转列表操作再转回字符串 循环内反复拼接
格式化 f-string %格式化(旧版)

✅ 总结要点

  1. 基础操作:索引切片、拼接、长度检测
  2. 核心方法:split(), join(), replace(), strip()
  3. 中文处理:切片长度按字符计算
  4. 性能关键:避免循环内拼接,多用