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

Python3 【字符串】:方法和函数使用示例手册

Python3 【字符串】:方法和函数使用示例手册

Python 提供了丰富的字符串处理方法和函数,以下是一些常用的方法和函数分类整理,并提供详细使用示例,简单易懂,值得收藏。


1. 字符串大小写转换

  • str.upper():将字符串转换为大写。
  • str.lower():将字符串转换为小写。
  • str.title():将每个单词的首字母大写。
  • str.capitalize():将字符串的第一个字符大写。
  • str.swapcase():交换字符串中的大小写。
s = "hello world"
print(s.upper())        # 输出 "HELLO WORLD"
print(s.title())        # 输出 "Hello World"
print(s.capitalize())   # 输出 "Hello world"

2. 字符串查找与替换

  • str.find(sub):返回子字符串 sub 第一次出现的索引,未找到返回 -1
  • str.rfind(sub):从右侧开始查找子字符串。
  • str.index(sub):与 find() 类似,但未找到时会抛出 ValueError
  • str.rindex(sub):从右侧开始查找。
  • str.replace(old, new):将字符串中的 old 替换为 new
  • str.count(sub):返回子字符串 sub 出现的次数。
s = "hello world"
print(s.find("world"))  # 输出 6
print(s.replace("world", "Python"))  # 输出 "hello Python"
print(s.count("l"))     # 输出 3

3. 字符串分割与连接

  • str.split(sep):根据分隔符 sep 将字符串分割为列表。
  • str.rsplit(sep):从右侧开始分割。
  • str.splitlines():按行分割字符串。
  • str.join(iterable):将可迭代对象中的元素用字符串连接。
s = "hello,world,python"
print(s.split(","))     # 输出 ['hello', 'world', 'python']
print("-".join(["a", "b", "c"]))  # 输出 "a-b-c"

4. 字符串去除空白与填充

  • str.strip():去除字符串两端的空白字符。
  • str.lstrip():去除左侧空白字符。
  • str.rstrip():去除右侧空白字符。
  • str.center(width):将字符串居中并用空格填充到指定宽度。
  • str.ljust(width):左对齐并用空格填充。
  • str.rjust(width):右对齐并用空格填充。
  • str.zfill(width):用 0 填充字符串到指定宽度。
s = "  hello  "
print(s.strip())        # 输出 "hello"
print(s.center(10))     # 输出 "  hello   "
print("42".zfill(5))    # 输出 "00042"

5. 字符串检查

  • str.startswith(prefix):检查字符串是否以 prefix 开头。
  • str.endswith(suffix):检查字符串是否以 suffix 结尾。
  • str.isalpha():检查字符串是否只包含字母。
  • str.isdigit():检查字符串是否只包含数字。
  • str.isalnum():检查字符串是否只包含字母和数字。
  • str.isspace():检查字符串是否只包含空白字符。
  • str.islower():检查字符串是否全为小写。
  • str.isupper():检查字符串是否全为大写。
s = "hello123"
print(s.startswith("he"))  # 输出 True
print(s.isalnum())         # 输出 True
print(s.isdigit())         # 输出 False

6. 字符串格式化

  • str.format():格式化字符串。
  • f-string(Python 3.6+):更简洁的格式化方式。
  • str % values:旧式格式化(不推荐)。
name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age))  # 输出 "Name: Alice, Age: 25"
print(f"Name: {name}, Age: {age}")            # 输出 "Name: Alice, Age: 25"

7. 字符串编码与解码

  • str.encode(encoding):将字符串编码为字节。
  • bytes.decode(encoding):将字节解码为字符串。
s = "hello"
encoded = s.encode("utf-8")  # 编码为字节
print(encoded)               # 输出 b'hello'
decoded = encoded.decode("utf-8")  # 解码为字符串
print(decoded)               # 输出 "hello"

8. 其他常用方法

  • len(str):返回字符串的长度。
  • str[::-1]:反转字符串。
  • str in str2:检查字符串是否包含子字符串。
  • str * n:重复字符串 n 次。
s = "hello"
print(len(s))        # 输出 5
print(s[::-1])       # 输出 "olleh"
print("he" in s)     # 输出 True
print(s * 3)         # 输出 "hellohellohello"

9. 字符串与列表的转换

  • list(str):将字符串转换为字符列表。
  • "".join(list):将字符列表合并为字符串。
s = "hello"
char_list = list(s)  # 转换为列表 ['h', 'e', 'l', 'l', 'o']
new_s = "".join(char_list)  # 合并为字符串 "hello"

10. 字符串的 Unicode 处理

  • ord(char):返回字符的 Unicode 码点。
  • chr(code):返回 Unicode 码点对应的字符。
print(ord("A"))  # 输出 65
print(chr(65))   # 输出 "A"

11. 字符串的切片操作

字符串切片是 Python 中非常强大且常用的功能,它允许你从字符串中提取子字符串。切片的基本语法是:

string[start:stop:step]
  • start:起始索引(包含)。
  • stop:结束索引(不包含)。
  • step:步长(可选,默认为 1)。

以下是更多关于切片的例子:


(1) 基本切片

s = "Python Programming"# 提取索引 0 到 5 的字符(不包含索引 6)
print(s[0:6])  # 输出 "Python"# 提取索引 7 到 18 的字符
print(s[7:18])  # 输出 "Programming"

(2) 省略起始或结束索引

  • 如果省略 start,默认从字符串开头开始。
  • 如果省略 stop,默认到字符串末尾结束。
s = "Python Programming"# 从开头到索引 5
print(s[:6])  # 输出 "Python"# 从索引 7 到末尾
print(s[7:])  # 输出 "Programming"# 提取整个字符串
print(s[:])  # 输出 "Python Programming"

(3) 使用负索引

负索引表示从字符串末尾开始计数(-1 是最后一个字符)。

s = "Python Programming"# 提取最后 5 个字符
print(s[-5:])  # 输出 "mming"# 提取从索引 -12 到 -1 的字符
print(s[-12:-1])  # 输出 "Programmin"

(4) 使用步长

步长 step 控制切片的间隔。

s = "Python Programming"# 提取所有字符,步长为 2
print(s[::2])  # 输出 "Pto rgamn"# 反转字符串
print(s[::-1])  # 输出 "gnimmargorP nohtyP"# 从索引 0 到 10,步长为 3
print(s[0:10:3])  # 输出 "Phr"

(5) 复杂切片

结合起始、结束和步长,可以实现更复杂的切片。

s = "Python Programming"# 从索引 2 到 12,步长为 2
print(s[2:12:2])  # 输出 "to rg"# 从索引 -10 到 -1,步长为 3
print(s[-10:-1:3])  # 输出 "rgn"

(6) 切片与字符串操作结合

切片可以与其他字符串操作结合使用。

s = "Python Programming"# 提取前 6 个字符并转换为大写
print(s[:6].upper())  # 输出 "PYTHON"# 提取最后 5 个字符并反转
print(s[-5:][::-1])  # 输出 "gnimm"

(7) 切片与条件结合

可以根据条件动态调整切片的范围。

s = "Python Programming"# 提取字符串的前半部分
half_length = len(s) // 2
print(s[:half_length])  # 输出 "Python Pro"# 提取字符串的后半部分
print(s[half_length:])  # 输出 "gramming"

(8) 多层切片

可以对切片结果再次切片。

s = "Python Programming"# 先提取 "Programming",再提取前 5 个字符
print(s[7:][:5])  # 输出 "Progr"

总结

Python 的字符串处理功能非常强大,涵盖了大小写转换、查找替换、分割连接、格式化、编码解码、切片处理等多种操作。掌握这些方法和函数,可以高效地处理各种字符串任务!

http://www.lryc.cn/news/524855.html

相关文章:

  • 数据结构与算法整理复习(一):数据结构概念与线性表
  • 【Block总结】PConv风车卷积,更大的感受野,提高特征提取能力|即插即用
  • Python新春烟花
  • VirtualBox can‘t enable the AMD-V extension
  • 掘金--创意标题匹配问题
  • OBU和T-Box
  • 【PVE】Proxmox VE8.0+创建LXC容器安装docker
  • 一文大白话讲清楚webpack基本使用——11——chunkIds和runtimeChunk
  • Java 中的设计模式:经典与现代实践
  • DRG_DIP 2.0时代医院程序结构转型与数据结构优化研究
  • 一部手机如何配置内网电脑同时访问内外网
  • 国产低功耗带LCD驱动和触摸按键功能的MCU
  • XCP 协议基础
  • Swift 中 Codable 和 Hashable 的理解
  • 基于 WPF 平台实现成语游戏
  • 2024“博客之星”——我的博客成长与技术洞察
  • HTTPS协议简述
  • 前沿技术趋势洞察:2024年技术的崭新篇章与未来走向!
  • HTML常用属性
  • 电子应用设计方案100:智能家庭AI电风扇系统设计
  • ThinkPHP 8请求处理-获取请求对象与请求上下文
  • 工厂模式 - 工厂方法模式、抽象工厂模式
  • 2025年已过6%
  • C#,入门教程(04)——Visual Studio 2022 数据编程实例:随机数与组合
  • UWB高精度定位技术在智能仓储中的应用
  • 计算机毕业设计hadoop+spark视频推荐系统 短视频推荐系统 视频流量预测系统 短视频爬虫 视频数据分析 视频可视化 视频大数据 大数据
  • 【AI编辑器】字节跳动推出AI IDE——Trae,专为中文开发者深度定制
  • CSDN 博客之星 2024:默语的技术进阶与社区耕耘之旅
  • 《探秘鸿蒙Next:非结构化数据处理与模型轻量化的完美适配》
  • async++库的使用示例