当前位置: 首页 > ai >正文

【Python 字符串】

Python 中的字符串(str)是用于处理文本数据的基础类型,具有不可变性、丰富的内置方法和灵活的操作方式。以下是 Python 字符串的核心知识点:


一、基础特性

  1. 定义方式

    s1 = '单引号字符串'
    s2 = "双引号字符串"
    s3 = '''三引号多行
    字符串'''
    s4 = """三引号多行
    字符串"""
    
  2. 不可变性

    s = "hello"
    s[0] = 'H'  # 报错:字符串不可修改
    
  3. 转义字符

    path = 'C:\\Users\\Name\\Documents'  # 反斜杠需转义
    text = "他说:\"Python 很有趣!\""    # 双引号需转义
    

二、常用操作

1. 字符串拼接
name = "Alice"
greeting = "Hello, " + name + "!"  # 拼接 → "Hello, Alice!"
2. 字符串重复
"Hi" * 3  # → "HiHiHi"
3. 成员检查
"a" in "apple"  # → True
4. 索引与切片
s = "Python"
s[0]    # → 'P'(正向索引,从0开始)
s[-1]   # → 'n'(反向索引,从-1开始)
s[1:4]  # → 'yth'(切片,左闭右开)
s[::-1] # → 'nohtyP'(逆序)

三、常用方法

1. 大小写转换
s = "hello World"
s.upper()   # → "HELLO WORLD"
s.lower()   # → "hello world"
s.title()   # → "Hello World"
2. 搜索与统计
s = "apple banana apple"
s.find("apple")  # → 0(首次出现位置)
s.count("apple") # → 2(出现次数)
s.startswith("ap") # → True
3. 替换与分割
s = "a,b,c,d"
s.replace(",", "-")  # → "a-b-c-d"
s.split(",")         # → ["a", "b", "c", "d"]
"-".join(["a", "b"]) # → "a-b"
4. 去除空白
s = "   hello   \n"
s.strip()   # → "hello"(去除首尾空白)
s.lstrip()  # → "hello   \n"(仅左侧)
s.rstrip()  # → "   hello"(仅右侧)

四、字符串格式化

1. f-string(推荐)
name = "Alice"
age = 25
f"姓名:{name},年龄:{age}"  # → "姓名:Alice,年龄:25"
2. str.format()
"{} is {} years old".format(name, age)  # → "Alice is 25 years old"
3. 百分号格式化
"数值:%.2f" % 3.1415  # → "数值:3.14"

五、编码处理

1. 编码转换
s = "你好"
bytes_data = s.encode("utf-8")  # → 字节串 b'\xe4\xbd\xa0\xe5\xa5\xbd'
original = bytes_data.decode("utf-8")  # → "你好"
2. 处理常见错误
# 忽略无法解码的字符
s = b'\xe4\xbd\xa0\xff'.decode("utf-8", errors="ignore")  # → "你"

六、高级技巧

1. 格式化对齐
s = "42"
s.rjust(5, '0')  # → "00042"(右对齐,填充0)
s.center(7, '-') # → "--42---"
2. 模板字符串(安全场景)
from string import Template
tpl = Template("Hello, $name!")
tpl.substitute(name="Bob")  # → "Hello, Bob!"
3. 路径操作(pathlib模块)
from pathlib import Path
path = Path("/user/docs/file.txt")
path.stem   # → "file"
path.suffix # → ".txt"

七、性能优化

  1. 避免频繁拼接

    # 低效方式
    res = ""
    for c in "long string":res += c# 高效方式
    parts = []
    for c in "long string":parts.append(c)
    "".join(parts)
    
  2. 预编译正则表达式(如需频繁匹配):

    import re
    pattern = re.compile(r"\d+")
    pattern.findall("a1b22c333")  # → ['1', '22', '333']
    

八、常见陷阱

  1. 索引越界

    s = "abc"
    s[3]  # 报错:IndexError
    
  2. 编码不一致

    # 错误示例:混合编码可能导致乱码
    with open("file.txt", "w", encoding="gbk") as f:f.write("你好")  # 需确保读写编码一致
    

通过掌握这些内容,可以高效处理文本数据,从简单的日志解析到复杂的自然语言处理任务。实际应用中需根据场景选择合适的方法,并注意编码和性能问题。

http://www.xdnf.cn/news/4607.html

相关文章:

  • Java常用API:深度解析与实践应用
  • 【Spring Boot 多模块项目】@MapperScan失效、MapperScannerConfigurer 报错终极解决方案
  • 安装 Docker
  • ZC706开发板教程:windows下编译ADRV9009
  • vue 中如何使用region?
  • PyTorch 实战:从 0 开始搭建 Transformer
  • 解决word里插入公式后打不开的问题
  • Linux-openeuler更换yum镜像源
  • uniapp + vue3 + 京东Nut动作面板组件:实现登录弹框组件(含代码、案例、小程序截图)
  • 村田与RohdeSchwarz联合开发用于测量Digital ET省电效果的RF系统
  • 网络化:DevOps 工程的必要基础(Networking: The Essential Foundation for DevOps Engineering)
  • 幂等的几种解决方案以及实践
  • STM32G070xx将Flash页分块方式存储,固定数据块存储,实现一次擦除多次写入
  • 【C语言】文件操作(续)
  • 一个用C#开发的记事本Notepads开源编辑器
  • Python实现中文数字与阿拉伯数字映射生成器(支持0-9999)
  • WebFlux与HttpStreamable关系解析
  • HuggingFace与自然语言处理(从框架学习到经典项目实践)[ 01 API操作 ]
  • 极简远程革命:节点小宝 — 无公网IP的极速内网穿透远程解决方案
  • 《开源先锋Apache软件基金会:历史沿革、顶级项目与行业影响》
  • 新能源汽车赛道变局:传统车企子品牌私有化背后的战略逻辑
  • java 破解aspose.words 18.6 使用
  • 如何使用 QuickAPI 推动医院数据共享 —— 基于数据仓库场景的实践
  • 学习笔记:数据库——事务
  • 启智平台调试 qwen3 4b ms-swift
  • 基于Kubernetes的Apache Pulsar云原生架构解析与集群部署指南(下)
  • IEEE出版|2025年通信网络与智能系统工程国际会议(CNSE2025)
  • uniapp中score-view中的文字无法换行问题。
  • 《spark》
  • 设计模式-策略模式