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

相关推荐
冷雨夜中漫步8 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴8 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再8 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
m0_7369191010 小时前
C++代码风格检查工具
开发语言·c++·算法
喵手10 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_9449347310 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy10 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
黎雁·泠崖11 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_7634724611 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
肖永威11 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos