Python 教程(三):字符串特性大全

[复制链接]
发表于 2026-2-18 16:26:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
在前两篇教程中,我们学习了 Python 的根本语法和数据结构。本篇教程,我们将深入探究 Python 中的字符串特性大全
专栏列表



  • Python教程(一):环境搭建及PyCharm安装
  • Python 教程(二):语法与数据结构
  • Python 教程(三):字符串特性大全


   正文开始 , 如果以为文章对您有资助,请帮我三连+订阅,谢谢💖💖💖
  
媒介

Python 3 中的字符串处理处罚功能非常强盛,提供了丰富的方法和操纵来处理处罚文本数据。下面我们将先容 字符串的 根本操纵、字符串方法、格式化、编码等等功能。
1. 字符串根本

字符串是 Python 中的一种不可变数据范例,用于存储文本数据。


  • 创建字符串:可以使用单引号或双引号来创建字符串。
  • 访问字符:通过索引访问字符串中的字符,索引从 0 开始。
  1. s = "Hello, World!"
  2. print(s[0])  # 输出: H
  3. print(s[7])  # 输出: W
复制代码

2. 字符串方法

Python 字符串对象提供了很多有用的方法,用于字符串的查询、修改和处理处罚。
字符串查询



  • str.find(sub):返回子字符串 sub 在字符串中初次出现的索引。
  • str.index(sub):雷同于 find(),但如果子字符串不存在则抛出 ValueError。
  • str.count(sub):返回子字符串在字符串中出现的次数。
  • str.startswith(prefix):查抄字符串是否以指定的前缀开始。
  • str.endswith(suffix):查抄字符串是否以指定的后缀竣事。
  1. s = "Hello, World!"
  2. print(s.find('o'))
  3. print(s.index('o'))
  4. print(s.count('o'))
  5. print(s.startswith('o'))
  6. print(s.endswith('o'))
复制代码

字符串修改



  • str.upper():将字符串中的全部字符转换为大写。
  • str.lower():将字符串中的全部字符转换为小写。
  • str.strip():移除字符串两端的空缺字符。
  • str.replace(old, new):更换字符串中的旧子字符串为新子字符串。
  1. s = "Hello, World!"
  2. print(s.upper())
  3. print(s.lower())
  4. print(s.strip())
  5. print(s.replace('o','K'))
复制代码

字符串切片



  • str[start:end]:获取字符串从索引 start 到 end-1 的子字符串。
  • str[start:]:获取字符串从索引 start 到末端的子字符串。
  • str[:end]:获取字符串从开始到索引 end-1 的子字符串。
  1. s = "Hello, World!"
  2. print(s[1:2])
  3. print(s[1:])
  4. print(s[:2])
复制代码

3. 字符串格式化

Python 3 提供了多种字符串格式化的方法。
旧式格式化(% 操纵符)

  1. name = "张胜男"
  2. age = 30
  3. print("Hello, %s. You are %d years old." % (name, age))
  4. # Hello, 张胜男. You are 30 years old.
复制代码
str.format() 方法

  1. name = "张胜男"
  2. age = 30
  3. print("Hello, {}. You are {} years old.".format(name, age))
复制代码
f-string(Python 3.6+)

  1. name = "张胜男"
  2. age = 30
  3. print(f"Hello, {name}. You are {age} years old.")
复制代码
4. 字符串编码

字符串可以编码为字节序列,反之亦然。


  • str.encode(encoding='utf-8'):将字符串编码为字节序列。
  • bytes.decode(encoding='utf-8'):将字节序列解码为字符串。
  1. s = "Hello, World!"
  2. encoded = s.encode('utf-8')
  3. print(encoded)  # 输出: b'Hello, World!'
  4. decoded = encoded.decode('utf-8')
  5. print(decoded)  # 输出: Hello, World!
复制代码
5. Unicode 和 ASCII

Python 3 默认使用 Unicode,可以处理处罚多种语言的字符。


  • ord(char):获取单个字符的 Unicode 编码。
  • chr(i):将 Unicode 编码转换为对应的字符。
  1. print(ord('A'))  # 输出: 65
  2. print(chr(65))  # 输出: A
复制代码
6. 正则表达式

Python 的 re 模块提供了正则表达式的支持,用于复杂的字符串匹配和处理处罚。
  1. import re
  2. pattern = r"\d+"
  3. result = re.findall(pattern, "有123个苹果和456个橙子")
  4. print(result)  # 输出: ['123', '456']
复制代码
7. 字符串比力

字符串比力是巨细写敏感的。
  1. s1 = "hello"
  2. s2 = "Hello"
  3. print(s1 == s2)  # 输出: False
复制代码
8. 字符串毗连

可以使用 + 操纵符毗连字符串。
  1. s1 = "Hello, "
  2. s2 = "World!"
  3. s3 = s1 + s2
  4. print(s3)  # 输出: Hello, World!
复制代码
9. 字符串不可变性

字符串是不可变的数据范例,这意味着一旦创建就不能更改。
  1. s = "Hello"
  2. s[0] = "h"  # TypeError: 'str' object does not support item assignment
复制代码
10. 字符串的内存视图

可以使用 bytes 和 bytearray 来处理处罚二进制数据。
  1. b = bytes([72, 101, 108, 108, 111])  # 等价于 b'Hello'
  2. ba = bytearray(b)
  3. ba[0] = 104  # 修改第一个字符为 'h'
  4. print(ba)  # 输出: bytearray(b'helli')
复制代码
总结

Python 3 提供了非常丰富的字符串处理处罚功能,从根本的字符串操纵到复杂的字符串格式化和正则表达式处理处罚。把握这些字符串处理处罚本领可以极大地进步你的编程服从和机动性。渴望这个梳理能资助你更好地明确和使用 Python 3 的字符串处理处罚功能。如果你有任何标题或须要进一步的资助,请随时接洽我们。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表