Appearance
第8章:字符串操作
8.1 字符串基础操作
字符串是Python中最常用的数据类型之一,用于存储文本数据。Python提供了丰富的字符串操作方法,使得字符串处理变得非常方便。
字符串拼接
- 语法:使用
+运算符拼接两个字符串 - 示例:python
str1 = "Hello" str2 = "Python" result = str1 + " " + str2 print(result) # 输出:Hello Python
字符串重复
- 语法:使用
*运算符重复字符串 - 示例:python
str1 = "a" result = str1 * 5 print(result) # 输出:aaaaa
字符串切片
- 语法:
字符串[起始索引:结束索引:步长] - 参数:
起始索引:开始位置(默认为0)结束索引:结束位置(不包含,默认为字符串长度)步长:步长(默认为1)
- 示例:python
str1 = "Python" print(str1[0]) # 输出:P print(str1[1:4]) # 输出:yth print(str1[:3]) # 输出:Pyt print(str1[3:]) # 输出:hon print(str1[::2]) # 输出:Pto(步长为2) print(str1[::-1]) # 输出:nohtyP(反转字符串)
字符串长度
- 语法:使用
len()函数获取字符串长度 - 示例:python
str1 = "Python" print(len(str1)) # 输出:6
8.2 字符串常用方法
Python提供了许多内置的字符串方法,用于处理和操作字符串。
大小写转换
upper():将字符串转换为大写lower():将字符串转换为小写title():将字符串每个单词的首字母大写- 示例:python
str1 = "hello python" print(str1.upper()) # 输出:HELLO PYTHON print(str1.lower()) # 输出:hello python print(str1.title()) # 输出:Hello Python
查找与替换
find(sub):查找子串,返回第一次出现的索引,找不到返回-1replace(old, new):替换子串- 示例:python
str1 = "Hello Python, Python is great!" print(str1.find("Python")) # 输出:6 print(str1.find("Java")) # 输出:-1 print(str1.replace("Python", "Java")) # 输出:Hello Java, Java is great!
去除空格
strip():去除字符串两端的空格lstrip():去除字符串左端的空格rstrip():去除字符串右端的空格- 示例:python
str1 = " Hello Python " print(str1.strip()) # 输出:Hello Python print(str1.lstrip()) # 输出:Hello Python print(str1.rstrip()) # 输出: Hello Python
分割与拼接
split(sep):按指定分隔符分割字符串,返回列表join(iterable):将可迭代对象中的元素用字符串连接起来- 示例:python
str1 = "apple,banana,cherry" fruits = str1.split(",") print(fruits) # 输出:['apple', 'banana', 'cherry'] str2 = "-".join(fruits) print(str2) # 输出:apple-banana-cherry
其他常用方法
startswith(prefix):判断字符串是否以指定前缀开头endswith(suffix):判断字符串是否以指定后缀结尾isdigit():判断字符串是否只包含数字isalpha():判断字符串是否只包含字母isalnum():判断字符串是否只包含字母和数字- 示例:python
str1 = "Python123" print(str1.startswith("Py")) # 输出:True print(str1.endswith("3")) # 输出:True print(str1.isdigit()) # 输出:False print(str1.isalpha()) # 输出:False print(str1.isalnum()) # 输出:True
8.3 字符串格式化
字符串格式化是将变量插入到字符串中的过程,Python提供了多种字符串格式化方法。
%格式化
- 语法:使用
%运算符和格式化占位符 - 常用占位符:
%s:字符串%d:整数%f:浮点数%.nf:保留n位小数的浮点数
- 示例:python
name = "zhangsan" age = 18 height = 1.75 print("我的名字是%s,年龄是%d岁,身高是%.2f米" % (name, age, height)) # 输出:我的名字是zhangsan,年龄是18岁,身高是1.75米
format()方法
- 语法:使用
format()方法和占位符{} - 示例:python
name = "zhangsan" age = 18 height = 1.75 print("我的名字是{},年龄是{}岁,身高是{:.2f}米".format(name, age, height)) # 输出:我的名字是zhangsan,年龄是18岁,身高是1.75米 # 可以指定位置 print("我的名字是{0},年龄是{1}岁,身高是{2:.2f}米".format(name, age, height)) # 可以指定名称 print("我的名字是{name},年龄是{age}岁,身高是{height:.2f}米".format(name=name, age=age, height=height))
f-string格式化(推荐)
- 语法:使用
f或F前缀,在字符串中直接使用{变量名} - 优势:语法简洁,可读性高,是Python 3.6+推荐的格式化方式
- 示例:python
name = "zhangsan" age = 18 height = 1.75 print(f"我的名字是{name},年龄是{age}岁,身高是{height:.2f}米") # 输出:我的名字是zhangsan,年龄是18岁,身高是1.75米 # 可以在{}中进行表达式计算 print(f"{name}的年龄明年是{age + 1}岁") # 输出:zhangsan的年龄明年是19岁
实操案例:字符串拼接与格式化
案例:用户信息格式化输出
python
"""
用户信息格式化输出
功能:将用户信息格式化为美观的字符串
"""
# 定义用户信息
users = [
{"name": "张三", "age": 25, "gender": "男", "score": 85.5},
{"name": "李四", "age": 30, "gender": "女", "score": 92.0},
{"name": "王五", "age": 22, "gender": "男", "score": 78.5}
]
# 打印表头
print("=" * 50)
print(f"{'姓名':<10}{'年龄':<5}{'性别':<5}{'分数':<10}")
print("-" * 50)
# 打印用户信息
for user in users:
print(f"{user['name']:<10}{user['age']:<5}{user['gender']:<5}{user['score']:<10.1f}")
print("=" * 50)运行结果
==================================================
姓名 年龄 性别 分数
--------------------------------------------------
张三 25 男 85.5
李四 30 女 92.0
王五 22 男 78.5
==================================================实操案例:字符串清洗
案例:字符串清洗
python
"""
字符串清洗
功能:去除字符串中的空格、替换特定字符
"""
# 原始字符串
raw_string = " Python is a great programming language! "
print(f"原始字符串:'{raw_string}'")
# 去除两端空格
cleaned_string = raw_string.strip()
print(f"去除两端空格:'{cleaned_string}'")
# 替换空格为下划线
underscore_string = cleaned_string.replace(" ", "_")
print(f"替换空格为下划线:'{underscore_string}'")
# 转换为大写
upper_string = cleaned_string.upper()
print(f"转换为大写:'{upper_string}'")
# 分割字符串
words = cleaned_string.split(" ")
print(f"分割字符串:{words}")
# 拼接字符串
joined_string = "-".join(words)
print(f"拼接字符串:'{joined_string}'")运行结果
原始字符串:' Python is a great programming language! '
去除两端空格:'Python is a great programming language!'
替换空格为下划线:'Python_is_a_great_programming_language!'
转换为大写:'PYTHON IS A GREAT PROGRAMMING LANGUAGE!'
分割字符串:['Python', 'is', 'a', 'great', 'programming', 'language!']
拼接字符串:'Python-is-a-great-programming-language!'新手易错点
字符串切片索引错误:索引超出字符串长度会导致错误
pythonstr1 = "Python" print(str1[10]) # 错误:string index out of range字符串不可修改:字符串是不可变类型,不能直接修改单个字符
pythonstr1 = "Python" str1[0] = "p" # 错误:'str' object does not support item assignment格式化参数不匹配:格式化字符串时,参数数量和类型必须与占位符匹配
python# 错误示例 print("我的名字是%s,年龄是%d岁" % ("zhangsan")) # 错误:not enough arguments for format string print("我的名字是%s,年龄是%d岁" % ("zhangsan", "18")) # 错误:%d format: a number is required, not str
通过本章的学习,你已经掌握了Python的字符串操作,包括字符串的基础操作、常用方法和格式化方式。字符串是Python编程中非常重要的数据类型,掌握好字符串操作对于处理文本数据、用户输入等场景非常重要。在实际编程中,你会经常用到这些字符串操作方法来处理各种文本数据。
