第21集:字符串基础操作
本集学习目标
- 理解字符串的概念
- 掌握字符串的创建方法
- 学会字符串的索引和切片
- 掌握字符串的拼接和重复
- 理解字符串的不可变性
- 通过实际练习掌握字符串的基本操作
什么是字符串?
字符串(String)是Python中最常用的数据类型之一,用于表示文本数据。字符串是由字符组成的序列,可以包含字母、数字、符号、空格等。
字符串的特点
- 使用单引号
' '或 双引号" "创建 - 字符串是不可变的(一旦创建不能修改)
- 字符串是序列,可以索引和切片
- 字符串支持迭代(用for循环遍历)
创建字符串
基本创建方式
# 使用单引号
str1 = 'Hello World'
# 使用双引号
str2 = "Hello World"
# 两种方式等价
print(str1 == str2) # True为什么需要两种引号?
当字符串中包含引号时,使用另一种引号创建字符串。
# 字符串中包含单引号,使用双引号
str1 = "It's a nice day"
# 字符串中包含双引号,使用单引号
str2 = 'She said "Hello" to me'
# 如果两者都有,使用转义字符
str3 = "She said \"Hello\" and I'm happy"三引号字符串
使用三个单引号或三个双引号可以创建多行字符串。
# 多行字符串
str1 = '''这是第一行
这是第二行
这是第三行'''
print(str1)
# 也用于文档字符串
def 函数():
"""这是函数的文档字符串
可以写多行
"""
pass字符串的索引
什么是索引?
索引是访问字符串中单个字符的方式。Python使用从0开始的索引。
索引图示
字符串: H e l l o
正向索引: 0 1 2 3 4
反向索引: -5 -4 -3 -2 -1示例1:正向索引
text = "Python"
print(text[0]) # P(第一个字符)
print(text[1]) # y
print(text[5]) # n
# print(text[6]) # 错误:索引越界示例2:反向索引
text = "Python"
print(text[-1]) # n(最后一个字符)
print(text[-2]) # o
print(text[-6]) # P(第一个字符)索引越界
text = "Python"
# 错误:索引越界
# print(text[6]) # IndexError
# print(text[-7]) # IndexError字符串的切片
什么是切片?
切片是获取字符串子串(部分字符)的方式。
切片语法
字符串[开始:结束:步长]参数说明:
开始:切片的起始位置(包含)结束:切片的结束位置(不包含)步长:每隔多少个字符取一个(可选,默认为1)
示例3:基本切片
text = "Python Programming"
print(text[0:6]) # Python(索引0到5)
print(text[7:18]) # Programming(索引7到17)
print(text[:6]) # Python(从开头到索引5)
print(text[7:]) # Programming(从索引7到结尾)
print(text[:]) # Python Programming(整个字符串)示例4:使用步长
text = "Python Programming"
print(text[::2]) # Pto rgamn(每隔一个字符)
print(text[::3]) # Ph nrgm(每隔两个字符)
print(text[7:18:2]) # Pormig(从索引7到17,每隔一个字符)示例5:反向切片
text = "Python"
print(text[::-1]) # nohtyP(反转字符串)
print(text[::-2]) # nhyP(反转并每隔一个字符)
print(text[5:1:-1]) # noht(从索引5到2,反向)示例6:切片越界
切片越界不会报错,Python会自动调整。
text = "Python"
print(text[0:100]) # Python(自动调整到结尾)
print(text[-100:]) # Python(自动调整到开头)字符串的拼接
使用+号拼接
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # Hello World使用+=运算符
greeting = "Hello"
greeting += " "
greeting += "World"
print(greeting) # Hello World拼接多个字符串
first = "Python"
second = "is"
third = "awesome"
result = first + " " + second + " " + third
print(result) # Python is awesome字符串的重复
使用*号重复
text = "Hello"
print(text * 3) # HelloHelloHello
print(text * 5) # HelloHelloHelloHelloHello
print("-" * 20) # --------------------(常用于分隔线)结合拼接和重复
text = "Python"
result = text + " " * 3 + text
print(result) # Python Python(Python和Python中间有3个空格)字符串长度
使用len()函数
text = "Python"
print(len(text)) # 6
empty = ""
print(len(empty)) # 0(空字符串长度为0)计算多行字符串长度
text = """第一行
第二行
第三行"""
print(len(text)) # 14(包含换行符)字符串的遍历
使用for循环遍历
text = "Python"
for char in text:
print(char)输出:
P
y
t
h
o
n使用for循环和索引遍历
text = "Python"
for i in range(len(text)):
print(f"索引{i}:{text[i]}")输出:
索引0:P
索引1:y
索引2:t
索引3:h
索引4:o
索引5:n使用enumerate()
text = "Python"
for index, char in enumerate(text):
print(f"索引{index}:{char}")字符串的不可变性
什么是不可变?
字符串一旦创建,不能修改其内容。
示例7:尝试修改字符串(错误)
text = "Python"
# 错误:不能修改字符串
# text[0] = "J" # TypeError: 'str' object does not support item assignment正确的修改方式:创建新字符串
text = "Python"
# 方法1:拼接
new_text = "J" + text[1:]
print(new_text) # Jython
# 方法2:切片
new_text = text[:2] + "XX" + text[2:]
print(new_text) # PyXXthon实际应用案例
案例1:用户名验证
username = input("请输入用户名:")
# 检查用户名长度
if len(username) < 3:
print("用户名太短,至少3个字符")
elif len(username) > 20:
print("用户名太长,最多20个字符")
else:
print(f"用户名'{username}'有效,长度:{len(username)}")案例2:提取文件名和扩展名
filename = "document.pdf"
# 提取文件名(不含扩展名)
name = filename[:-4]
print(f"文件名:{name}")
# 提取扩展名
extension = filename[-4:]
print(f"扩展名:{extension}")
# 更通用的方法
dot_index = filename.rfind('.')
name = filename[:dot_index]
extension = filename[dot_index:]
print(f"文件名:{name},扩展名:{extension}")案例3:生成分隔线
title = "标题"
# 动态生成分隔线
separator = "=" * len(title)
print(separator)
print(title)
print(separator)输出:
```
标题
### 案例4:格式化输出
```python
name = "张三"
age = 18
# 使用f-string格式化
print(f"姓名:{name}")
print(f"年龄:{age}岁")
print(f"姓名:{name},年龄:{age}岁")案例5:反转字符串
text = "Python"
# 方法1:使用切片
reversed_text = text[::-1]
print(f"原字符串:{text}")
print(f"反转后:{reversed_text}")
# 方法2:使用循环
reversed_text = ""
for char in text:
reversed_text = char + reversed_text
print(f"反转后:{reversed_text}")常见错误与注意事项
错误1:索引越界
text = "Python"
# 错误:索引越界
# print(text[6]) # IndexError解决方法:使用len()检查长度
text = "Python"
if len(text) > 6:
print(text[6])
else:
print("索引越界")错误2:尝试修改字符串
text = "Python"
# 错误:字符串不可变
# text[0] = "J" # TypeError解决方法:创建新字符串
text = "Python"
new_text = "J" + text[1:]
print(new_text) # Jython错误3:混淆切片的结束位置
text = "Python"
print(text[0:6]) # Python(0到5,不包含6)
# print(text[0:5]) # Pytho(如果以为是0到6就错了)本集小结
- 字符串是Python中最常用的数据类型之一
- 使用单引号或双引号创建字符串
- 字符串是不可变的
- 索引从0开始,支持正向和反向索引
- 切片可以获取子串,语法为
[开始:结束:步长] - 使用
+拼接字符串,使用*重复字符串 - 使用
len()获取字符串长度 - 使用
for循环遍历字符串 - 使用
[::-1]可以反转字符串
课后练习
练习1:索引访问
给定字符串"Python",输出:
- 第一个字符
- 最后一个字符
- 第三个字符
text = "Python"
# 你的代码在这里练习2:切片操作
给定字符串"Python Programming",输出:
- "Python"
- "Programming"
- "Pythn"(每隔一个字符)
- 反转后的字符串
text = "Python Programming"
# 你的代码在这里练习3:拼接字符串
将三个字符串拼接成一个完整的句子。
word1 = "Python"
word2 = "is"
word3 = "awesome"
# 拼接成 "Python is awesome"练习4:重复字符串
使用字符串重复生成一条分隔线。
# 生成20个"="的字符串
separator = "=" * 20
print(separator)练习5:提取信息
从文件名"my_document.pdf"中提取文件名和扩展名。
filename = "my_document.pdf"
# 提取文件名 "my_document" 和扩展名 ".pdf"下集预告
下一集我们将学习第22集:字符串常用方法。Python提供了大量的字符串方法,可以方便地处理字符串,如大小写转换、查找、替换、分割等。
敬请期待!