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

相关推荐
宵时待雨1 分钟前
C语言笔记归纳21:编译与链接
linux·c语言·开发语言·笔记
天勤量化大唯粉2 分钟前
基于距离的配对交易策略:捕捉价差异常偏离的均值回归机会(天勤量化代码实现)
android·开发语言·python·算法·kotlin·开源软件·策略模式
leiming67 分钟前
c++ 利用模板创建一个可以储存任意类型数据的数组类
开发语言·c++·算法
无敌最俊朗@7 分钟前
音视频C++开发进阶指南
开发语言·c++·音视频
Bruce_Liuxiaowei8 分钟前
Python 跨平台 Nmap 自动化扫描工具:从手动到一键批量扫描
开发语言·python·网络安全·自动化
待╮續9 分钟前
Conda 使用教程
python
派大鑫wink11 分钟前
【Day1】Java 入门:开发环境搭建(JDK 安装 + IDEA 配置 + HelloWorld 实战)
java·开发语言·intellij-idea
lingran__11 分钟前
C语言内存函数详解
c语言·开发语言
lsx20240612 分钟前
R JSON 文件
开发语言