day05 课程(字符串 & 切片 & 字符串常用操作)

课程:https://www.bilibili.com/video/BV1o4411M71o?spm_id_from=333.788.videopod.episodes&p=94

5.1 学习字符串的必要性

5.1.1 目标

  认识字符串

  下标

  切片

  常用操作方法

5.2 认识字符串

字符串是 Python 中最常用的数据类型,一般使用引号来创建字符串,创建字符串很简单,只要为变量分配一个值既可

a = 'hello world'  # 单引号
b = "abcdefg"  # 双引号
print(type(a))
print(type(b))

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\01.认识字符串.py 
<class 'str'>
<class 'str'>

Process finished with exit code 0

注意:控制台显示结果为 <class 'str'>,即数据类型为 str(字符串)

a = ('hello '
     'world')  # 换行,前后自动增加了单引号
print(a)  # 输出时不换行
print(type(a))

# 三单引号
e = '''i am tom'''
print(type(e))

# 三双引号
f = """I 
am TOM"""  # 换行,不增加引号
print(f)  # 输出时带有换行
print(type(f))

# I'm TOM
g = "I'm TOM"
print(g)

h = 'I\'m TOM'  # 引号成对出现,字符串中带有引号 需要使用转义字符 \
print(h)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\01.认识字符串.py 
hello world
<class 'str'>
<class 'str'>
I 
am TOM
<class 'str'>
I'm TOM
I'm TOM

Process finished with exit code 0

注意:三引号形式的字符串支持换行

5.3 字符串输出

print("hello world")

name = "TOM"
print("我的名字是 %s" % name)  # 占位符的格式化输出
print(f"我的名字是 {name}")  # f 的格式化输出

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\02.字符串输出.py 
hello world
我的名字是 TOM
我的名字是 TOM

Process finished with exit code 0

5.4 字符串输入

在 Python 中,使用 input() 接收用户输入

# 输入密码
password = input("请输入密码:")  # 无论输入字母还是数字,都是字符串类型
print(f"输入的密码是{password}")
print(type(password))

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\03.字符串输入.py 
请输入密码:123456  # 控制台输入
输入的密码是123456
<class 'str'>

Process finished with exit code 0

5.5 下标

“下标” 又叫 “索引”,就是编号,比如火车座位号,座位号的作用:按照编号快速找到对应的座位,同理,下标的作用即是通过下标快速找到对应的数据

str1 = 'abcdefg'
print(str1)

# 数据在程序运行过程中存储在内存,这些字符数据从0开始顺序分配一个编号
# 得到某个字符,数据 a 字符 -> 数据.[下标] -> str1[1]
print(str1[0])
print(str1[1])

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\04.下标.py 
abcdefg
a
b

Process finished with exit code 0

注意:下标从 0 开始,列表、元组 中也有下标

5.6 切片简介

切片是指对操作的对象截取其中一部分的操作,字符串、列表、元组 都支持切片操作

5.6.1 切片语法

序列[开始位置下标:结束位置下标:步长]

注意: 

  1.不包含结束位置下标对应的数据(左闭右开),正负整数均可

  2.步长是选取间隔,正负整数均可,默认步长为1

5.7 体验切片

# 序列[开始位置下标:结束位置下标:步长]
str1 = "012345678"
print(str1[2:5:1])  # 结果 234 ,左闭右开, 5 没有拿到
print(str1[2:5:2])  # 结果 24 ,测试 步长取值
print(str1[2:5])  # 结果 234 ,默认步长为 1,可以不写
print(str1[:5])  # 结果 01234 ,不写开始,默认从索引0开始选取
print(str1[2:])  # 结果 2345678 ,不写结束,默认选取到最后
print(str1[:])  # 结果 012345678 ,不写开始和结束,表示选取所有

# 负数测试
print(str1[::-1])  # 结果 876543210 ,选取步长为负数,倒序选取
print(str1[-4:-1])  # 结果 567 ,下标 -1 表示最后一个数据,依次向前类推
                    # 8 为 -1, 7 为 -2, 6 为 -3, 5 为 -4 左闭右开 取 567
print(str1[-4:-1:-1])  # 结果 空 ,不能选取出数据,从 -4 开始到 -1 结束,选取方向从左侧到右侧,但是 -1 步长,从右侧向左侧选取
# *** 如果选取方向(下标开始到结束的方向) 和 步长的方向冲突,则 无法选取数据
print(str1[-1:-4:-1])  # 结果 876 , -1 到 -4 从右侧向左侧, 步长 -1 ,从右侧向左侧, 选取方向一致

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\06.体验切片.py 
234
24
234
01234
2345678
012345678
876543210
567

876

Process finished with exit code 0

5.8 字符串常用方法简介

字符串的常用操作方法有查找、修改和判断三大类

5.9 字符串常用操作方法之查找

字符串查找方法即是查找子串在字符串中的位置或出现的次数

5.9.1 find

find():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始位置的下标,否则则返回 -1

(1)语法

字符串序列.find(查找子串,开始位置下标,结束位置下标)

注意:开始位置和结束位置下标可以省略,表示在整个字符串序列中查找

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

print(mystr.find('and'))  # 返回结果 12 , 查找到第一个 and 开始的下标字符是 12
print(mystr.find('and', 15 , 30))  # 返回结果 23 , 即字符串 从" itcast and ith"之间 查找 and
print(mystr.find('ands'))  # 返回结果 -1 ,ands 子串不存在

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\07.字符串常用操作方法之查找.py 
12
23
-1

Process finished with exit code 0

5.9.2 index

index():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下标,否则则报异常

(1)语法

字符串序列.index(查找子串,开始位置下标,结束位置下标)

注意:开始位置和结束位置下标可以省略,表示在整个字符串序列中查找

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

print(mystr.index('and'))  # 返回结果 12 , 查找到第一个 and 开始的下标字符是 12
print(mystr.index('and', 15 , 30))  # 返回结果 23 , 即字符串 从" itcast and ith"之间 查找 and
print(mystr.index('ands'))  # 如果 index 查找子串不存在,报错

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\07.字符串常用操作方法之查找.py 
12
23
Traceback (most recent call last):
  File "D:\Pycharm\code\day05\07.字符串常用操作方法之查找.py", line 15, in <module>
    print(mystr.index('ands'))  # 如果 index 查找子串不存在,报错
          ~~~~~~~~~~~^^^^^^^^
ValueError: substring not found

Process finished with exit code 1

5.9.3 count

(1)语法

字符串序列.count(查找子串,开始位置下标,结束位置下标)

注意:开始位置和结束位置下标可以省略,表示在整个字符串序列中查找

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

print(mystr.count('and', 15 , 30))  # 返回结果 1 ,15 到 30 之间只有1个
print(mystr.count('and'))  # 返回结果 3 ,总共出现了 3 次
print(mystr.count('ands'))  # 返回结果 0

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\07.字符串常用操作方法之查找.py 
1
3
0

Process finished with exit code 0

5.9.4 逆向

 rfind():和 find() 功能相同,但查找方向为右侧开始

 rindex():和 index() 功能相同,但查找方向为 右侧开始

 count():返回某个子串在字符串中出现的次数

mystr = "hello world and itcast and itheima and Python"

print(mystr.rfind("and"))  # 返回结果 35, 右边第一个 and 位置 ,下标从左边开始计算
print(mystr.rfind("ands"))  # 返回结果 -1 ,ands 子串不存在,与 find 相同

print(mystr.rindex("and"))  # 返回结果 35, 右边第一个 and 位置 ,下标从左边开始计算
print(mystr.rindex("ands"))  # 如果 rindex 查找子串不存在,报错

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\07.字符串常用操作方法之查找.py 
35
-1
35
Traceback (most recent call last):
  File "D:\Pycharm\code\day05\07.字符串常用操作方法之查找.py", line 30, in <module>
    print(mystr.rindex("ands"))  # 返回结果 -1 ,ands 子串不存在,与 find 相同
          ~~~~~~~~~~~~^^^^^^^^
ValueError: substring not found

Process finished with exit code 1

5.10 字符串常用操作方法之修改

修改字符串,指的是通过函数的形式修改字符串中的数据

5.10.1 replace

replace():替换

(1)语法

字符串序列.replace(旧子串, 新子串, 替换次数)

注意:替换次数如果查出子串出现次数,则替换次数为该子串出现次数

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

# replace() 把 and 替换成 和
mystr.replace("and","")
new_str1 = mystr.replace("and","")  # 与上面对比,说明 replace 函数有返回值,返回值是修改后的字符串
new_str2 = mystr.replace("and","",1)
new_str3 = mystr.replace("and","",10)

print(mystr)  # 直接调用 replace()函数,原字符串的数据没有修改
print(new_str1)  # 修改后的数据是 replace 函数的返回值
print(new_str2)  # 只修改 1 次,其他不修改
print(new_str3)  # 替换次数超出子串出现次数,则替换所有

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\08.字符串常用操作方法之修改.py 
hello world and itcast and itheima and Python
hello world 和 itcast 和 itheima 和 Python
hello world 和 itcast and itheima and Python
hello world 和 itcast 和 itheima 和 Python

Process finished with exit code 0

注意:数据按照是否能直接修改分为 可变类型不可变类型 两种,字符串类型的数据修改的时候不能改变原有字符串,属于不能直接修改数据的类型,即不可变类型

5.10.2 split

split():按照指定字符分割字符串

(1)语法

字符串序列.split(分割字符, num)

注意:num 表示分割字符出现的次数,即将来返回数据个数为 num+ 1 个

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

str1 = mystr.split('and')  # 分割 返回一个列表,丢失分割的字符 and
str2 = mystr.split('and', 2)  # 按顺序切割 2 次,返回 2 + 1,即 3 个数据
print(str1)
print(str2)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\08.字符串常用操作方法之修改.py 
['hello world ', ' itcast ', ' itheima ', ' Python']
['hello world ', ' itcast ', ' itheima and Python']

Process finished with exit code 0

注意:如果分割字符是原有字符串中的子串,分割后则丢失该子串

5.10.3 join

join():用一个字符或子串合并字符串,即将多个字符串合并为一个新的字符串

(1)语法

字符或子串.join(多字符串组成的序列)

(2)快速体验

mylist = ["aa","bb","cc"]

# 拼接 aa...bb...cc
mylist1 = "..".join(mylist)
print(mylist1)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\08.字符串常用操作方法之修改.py 
aa..bb..cc

Process finished with exit code 0

5.11 字符串常用操作方法之修改大小写转换

5.11.1 capitalize

capitalize():将字符串第一个字符转换成大写

mystr = "hello world and itcast and itheima and Python"

print(mystr)
mystr1 = mystr.capitalize()  # 字符串中首字母大写,其他大写都转换成了小写 Python
print(mystr1)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\09.字符串常用操作方法之修改大小写转换.py 
hello world and itcast and itheima and Python
Hello world and itcast and itheima and python

Process finished with exit code 0

5.11.2 title

title():将字符串每个单词首字母转换成大写

mystr = "hello world and itcast and itheima and Python"

print(mystr)
mystr2 = mystr.title()  # 字符串中每个单词首字母大写
print(mystr2)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\09.字符串常用操作方法之修改大小写转换.py 
hello world and itcast and itheima and Python
Hello World And Itcast And Itheima And Python

Process finished with exit code 0

5.11.3 lower

lower():将字符串中大写转小写

mystr = "hello world and itcast and itheima and Python"

print(mystr)
mystr3 = mystr.lower()  # 字符串中所有单词字母转小写
print(mystr3)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\09.字符串常用操作方法之修改大小写转换.py 
hello world and itcast and itheima and Python
hello world and itcast and itheima and python

Process finished with exit code 0

5.11.4 upper

upper():将字符串中小写转大写

mystr = "hello world and itcast and itheima and Python"

print(mystr)
mystr4 = mystr.upper()  # 字符串中所有单词字母转大写
print(mystr4)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\09.字符串常用操作方法之修改大小写转换.py 
hello world and itcast and itheima and Python
HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON

Process finished with exit code 0

5.12 字符串常用操作方法之修改之删除空白字符

5.12.1 lstrip

lstrip():删除字符串左侧空白字符,left 左边

mystr = "    hello world and itcast and itheima and Python   "

print(mystr)
mystr1 = mystr.lstrip()  # 删除左侧空白字符
print(mystr1)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\10.字符串常用操作方法之修改之删除空白字符.py 
    hello world and itcast and itheima and Python   
hello world and itcast and itheima and Python   

Process finished with exit code 0

5.12.2 rstrip

rstrip():删除字符串右侧空白字符,right 右边

mystr = "    hello world and itcast and itheima and Python   "

print(mystr)
mystr2 = mystr.rstrip()  # 删除右侧空白字符
print(mystr2)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\10.字符串常用操作方法之修改之删除空白字符.py 
    hello world and itcast and itheima and Python   
    hello world and itcast and itheima and Python

Process finished with exit code 0

5.12.3 strip

strip():删除字符串两侧空白字符

mystr = "    hello world and itcast and itheima and Python   "

print(mystr)
mystr3 = mystr.strip()  # 删除两侧空白字符
print(mystr3)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\10.字符串常用操作方法之修改之删除空白字符.py 
    hello world and itcast and itheima and Python   
hello world and itcast and itheima and Python

Process finished with exit code 0

5.13 字符串常用操作方法之修改之字符串对齐

5.13.1 ljust

ljust():返回一个原字符串左对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,left 左边

(1)语法

字符串序列.ljust(长度, 填充字符)

(2)快速体验

mystr = 'hello'

print(mystr)
mystr1 = mystr.ljust(10)
print(mystr1)
mystr2 = mystr.ljust(10,'_')
print(mystr2)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\11.字符串常用操作方法之修改之字符串对齐.py 
hello
hello     
hello_____

Process finished with exit code 0

5.13.2 rjust

rjust():返回一个原字符串右对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和ljust()相同

(1)语法

字符串序列.rjust(长度, 填充字符)

(2)快速体验

mystr = 'hello'

print(mystr)
mystr1 = mystr.rjust(10)
print(mystr1)
mystr2 = mystr.rjust(10,'.')
print(mystr2)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\11.字符串常用操作方法之修改之字符串对齐.py 
hello
     hello
.....hello

Process finished with exit code 0

5.13.1 center

center():返回一个原字符串居中对齐,并使用指定字符(默认空格)填充至对应长度的新字符串,语法和ljust()相同

(1)语法

字符串序列.center(长度, 填充字符)

(2)快速体验

mystr = 'hello'

print(mystr)
mystr1 = mystr.center(10)
print(mystr1)
mystr2 = mystr.center(10,'.')  # 左边两个. 右边三个. 并不能做到绝对居中
print(mystr2)

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\11.字符串常用操作方法之修改之字符串对齐.py 
hello
  hello   
..hello...

Process finished with exit code 0

5.14 字符串常用操作方法之判断开头或结尾

判断即判断真假,返回的结果是布尔型数据类型:True 或 False

5.14.1 startswith

startswith():检查字符串是否是以指定子串开头,是则返回 True,否则返回 False,如果设置开始和结束位置下标,则在指定范围内检查

(1)语法

字符串序列.startswith(子串, 开始位置下标, 结束位置下标)  # 位置下标可以省略

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

print(mystr)
print(mystr.startswith("hello"))  # 以 hello 开头 True
print(mystr.startswith("hel"))  # 以 hel 开头 True
print(mystr.startswith("hels"))  # 以 hels 开头 False

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\12.字符串常用操作方法之判断开头或结尾.py 
hello world and itcast and itheima and Python   
True
True
False

Process finished with exit code 0

5.14.2 endswith

(1)语法

字符串序列.endswith(子串, 开始位置下标, 结束位置下标)  # 位置下标可以省略

(2)快速体验

mystr = "hello world and itcast and itheima and Python"

print(mystr)
print(mystr.endswith("Python"))  # 以 Python 结尾 True
print(mystr.endswith("Pythons"))  # 以 Pythons 结尾 False

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\12.字符串常用操作方法之判断开头或结尾.py 
hello world and itcast and itheima and Python
True
False

Process finished with exit code 0

5.15 字符串常用操作方法之判断

5.15.1 isalpha

isalpha():如果字符串至少有一个字符并且所有字符都是字母则返回 True,否则返回 False

mystr1 = "hello world and itcast and itheima and Python"
mystr2="     "
mystr3="abcdefg"

print(mystr1.isalpha())  # 有空格 返回 False
print(mystr2.isalpha())  # 都是空格 返回 False
print(mystr3.isalpha())  # 都是字母 返回 True

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\13.字符串常用操作方法之判断.py 
False
False
True

Process finished with exit code 0

5.15.2 isdigit

isdigit():如果字符串只包含数字则返回 True 否则返回 False

mystr1 = "hello world and itcast and itheima and Python"
mystr2 = "123456abcdef"
mystr3 = "123456"

print(mystr1.isdigit())  # 是字母 返回 False
print(mystr2.isdigit())  # 是数字字母组合 返回 False
print(mystr3.isdigit())  # 是数字 返回 True

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\13.字符串常用操作方法之判断.py 
False
False
True

Process finished with exit code 0

5.15.3 isalnum

isalnum():如果字符串中至少有一个字符并且所有字符都是字母或数字或字母数字组合则返回 True,否则返回 False

mystr1 = "hello world and itcast and itheima and Python"
mystr2 = "123456abcdef"
mystr3 = "123456"

print(mystr1.isalnum())  # 有空格 返回 False
print(mystr2.isalnum())  # 是数字字母组合 返回 True
print(mystr3.isalnum())  # 是数字 返回 True

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\13.字符串常用操作方法之判断.py 
False
True
True

Process finished with exit code 0

5.15.4 isspace

isspace():如果字符串中只包含空白,则返回 True,否则返回 False

mystr1 = "hello world and itcast and itheima and Python"
mystr2 = "123456abcdef"
mystr3 = "123456"
mystr4 = "    "

print(mystr1.isspace())  # 有空格字母 返回 False
print(mystr2.isspace())  # 有数字字母 返回 False
print(mystr3.isspace())  # 有数字 返回 False
print(mystr4.isspace())  # 是空格 返回 True

------------------------------------------------ 执行后
C:\Users\马俊南\AppData\Local\Microsoft\WindowsApps\python3.13.exe D:\Pycharm\code\day05\13.字符串常用操作方法之判断.py 
False
False
False
True

Process finished with exit code 0

5.16 字符串总结

下标:

  计算机为数据序列中每个元素分配的从 0 开始的编号

切片:

  序列名[开始位置下标:结束位置下标:步长]

常用操作方法:

  find()

  index()

———————————————————————————————————————————————————————————————————————————

                                                                                                                         无敌小马爱学习

posted on 2025-09-11 17:27  马俊南  阅读(12)  评论(0)    收藏  举报