【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中字符串操作的一部分,但它们是处理文本数据时最常用的方法。

相关推荐
Sammyyyyy7 分钟前
2025年,Javascript后端应该用 Bun、Node.js 还是 Deno?
开发语言·javascript·node.js
站大爷IP14 分钟前
Python与MySQL:从基础操作到实战技巧的完整指南
python
老歌老听老掉牙18 分钟前
SymPy 矩阵到 NumPy 数组的全面转换指南
python·线性代数·矩阵·numpy·sympy
站大爷IP23 分钟前
Python条件判断:从基础到进阶的实用指南
python
赛博郎中28 分钟前
pygame小游戏飞机大战_8继承精灵玩家优化
python·pygame
William一直在路上39 分钟前
Python数据类型转换详解:从基础到实践
开发语言·python
看到我,请让我去学习1 小时前
Qt— 布局综合项目(Splitter,Stacked,Dock)
开发语言·qt
GUET_一路向前2 小时前
【C语言防御性编程】if条件常量在前,变量在后
c语言·开发语言·if-else·防御性编程
曳渔2 小时前
UDP/TCP套接字编程简单实战指南
java·开发语言·网络·网络协议·tcp/ip·udp
trayvontang2 小时前
Python虚拟环境与包管理工具(uv、Conda)
python·conda·uv·虚拟环境·miniconda·miniforge