【7.2 python中的字符串常用操作】

python中的字符串常用操作


Python中的字符串(str 类型)提供了丰富的操作方法来处理文本数据。以下是一些常用的字符串操作:

1. 字符串拼接

  • 使用加号(+)操作符可以将两个或多个字符串拼接成一个新的字符串。
python 复制代码
s1 = "Hello, "
s2 = "world!"
s3 = s1 + s2  # 结果为 "Hello, world!"

2. 字符串重复

  • 使用乘号(*)操作符可以将字符串重复指定的次数。
python 复制代码
s = "abc"
repeated_s = s * 3  # 结果为 "abcabcabc"

3. 字符串索引

  • 可以通过索引(索引从0开始)访问字符串中的单个字符。
python 复制代码
s = "hello"
print(s[0])  # 输出 'h'
print(s[-1])  # 输出 'o',负索引表示从字符串末尾开始计数

4. 字符串切片

  • 切片操作允许你获取字符串的一个子串。
python 复制代码
s = "hello world"
print(s[0:5])  # 输出 'hello',从索引0到索引5(不包括索引5)
print(s[6:])   # 输出 'world',从索引6到字符串末尾
print(s[:-6])  # 输出 'hello ',从索引0到索引-6(不包括索引-6)

5. 字符串长度

  • 使用 len() 函数可以获取字符串的长度(即包含的字符数)。
python 复制代码
s = "hello"
print(len(s))  # 输出 5

6. 字符串查找

  • find() 方法用于查找子串在字符串中的位置(索引),如果未找到则返回 -1
  • index() 方法与 find() 类似,但如果未找到子串则会引发 ValueError
python 复制代码
s = "hello world"
print(s.find("world"))  # 输出 6
print(s.index("python"))  # 抛出 ValueError

7. 字符串替换

  • replace() 方法用于替换字符串中的某些字符或子串。
python 复制代码
s = "hello world"
new_s = s.replace("world", "Python")  # 结果为 "hello Python"

8. 字符串分割

  • split() 方法用于将字符串分割成子串列表,默认按空白字符(空格、换行符等)分割。
python 复制代码
s = "apple,banana,cherry"
fruits = s.split(",")  # 结果为 ['apple', 'banana', 'cherry']

9. 字符串格式化

  • Python 提供了多种字符串格式化方法,如 % 操作符、str.format() 方法以及 f-string(Python 3.6+)。
python 复制代码
name = "Alice"
age = 30
# 使用 % 操作符
s = "Name: %s, Age: %d" % (name, age)
# 使用 str.format()
s = "Name: {}, Age: {}".format(name, age)
# 使用 f-string
s = f"Name: {name}, Age: {age}"

10. 字符串去空格

  • strip() 方法用于去除字符串两端的空白字符(包括空格、换行符等)。
  • lstrip()rstrip() 分别用于去除字符串左端和右端的空白字符。
python 复制代码
s = "   hello world   "
print(s.strip())  # 输出 'hello world'

11. 字符串大小写转换

  • upper() 方法将字符串中的所有小写字母转换为大写字母。
  • lower() 方法将字符串中的所有大写字母转换为小写字母。
  • capitalize() 方法将字符串的第一个字符转换为大写字母,其余字符转换为小写字母。
  • title() 方法将字符串中每个单词的首字母转换为大写字母,其余字符转换为小写字母。
python 复制代码
s = "hello world"
print(s.upper())  # 输出 'HELLO WORLD'
print(s.lower())  # 输出 'hello world'
print(s.capitalize())  # 输出 'Hello world'
print(s.title())  # 输出 'Hello World'

这些只是Python中字符串操作的一部分,但它们是处理文本数据时最常用的方法。

相关推荐
小何code8 小时前
人工智能【第8篇】监督学习实战:线性回归与逻辑回归算法详解(万字长文+完整代码实现)
人工智能·python·学习·机器学习·逻辑回归·线性回归
EnCi Zheng8 小时前
M5-markconv自定义CSS样式指南 [特殊字符]
前端·css·python
DevilSeagull8 小时前
Windows 批处理 (Batch) 编程: 从入门到入土. (一) 基础概念与环境配置
开发语言·windows·后端·batch·语言
AI科技星8 小时前
全域数学·第卷:场计算机卷(场空间计算机)【乖乖数学】
java·开发语言·人工智能·算法·机器学习·数学建模·数据挖掘
刘~浪地球8 小时前
DeepSeek V4 应用实战:构建智能数据分析Agent
python·数据挖掘·数据分析
charlie1145141918 小时前
嵌入式C++实践开发第21篇(单片机实践):按钮输入 —— 硬件原理、消抖与HAL API
开发语言·c++·单片机
前端老石人8 小时前
前端开发中的 URL 完全指南
开发语言·前端·javascript·css·html
0xDevNull8 小时前
Java泛型详解
java·开发语言·后端
嘻嘻哈哈樱桃8 小时前
牛客经典101题解题集--贪心算法+模拟
java·python·算法·贪心算法
yeeanna8 小时前
GO函数的特殊性
开发语言·后端·golang