第五天 字符串的学习 |
学习目的:
一、字符串的学习(下标、切片、常用的操作方法)
二、列表的学习(列表的应用场景、列表的格式、列表的常用操作、列表的循环遍历、列表的嵌套使用)
一、学习字符串的必要性
爬虫,input()等数据来源大多是字符串;认识字符串,用'字符串'
,为变量分配一个值。
单引号、双引号、单三引号、双三引号打印出来的数据都是字符串类型
print('单引号的数据不支持回车换行')
a1 = 'Hello girl!'
print(a1) # Hello girl!
a2 = 'Hello ' \
'girl!'
print(a2) # Hello girl!
print('双引号的数据不支持回车换行')
b1 = "Hello boy!"
print(b1) # Hello boy!
b2 = "Hello " \
"boy!"
print(b2) # Hello boy!
print('单三引号的数据支持回车换行')
c1 = '''Hello children!'''
print(c1) # Hello children!
c2 = '''Hello
children!'''
print(c2)
# Hello
# children!
print('双三引号的数据支持回车换行')
d1 = """Hello children!"""
print(d1) # Hello children!
d2 = """Hello
children!"""
print(d2) # Hello children!
# Hello
# children!
总结
1、只有三引号的数据支持回车换行
2、若是字符串中有’,例如I‘m Tom.,此时可以写成c="I'm Tom."
或'I\'m Tom.'
print('字符串里有单引号的用法--使用""或者直接加\ ')
c="I'm Tom"
d= 'I\'m Tom'
print(c)
print(d)
3、三引号换行的时候,下一行是否顶格取决于自己从哪换行(空格也占位号)
结果:
二、字符串的输出和输入
# 字符串的输出
print('hello world')
name = 'Tom'
print('我的名字是%s' % name) # 我的名字是Tom
print(f'我的名字是{name}') # 我的名字是Tom
# 字符串的输入
password = input('请输入您的密码:')
print(f'您输入的密码是{password}')
print(type(password)) # <class 'str'>
三、下标
字符串、列表、元组都会用到下标!下标又叫索引,作用是:通过下标可以快速找到对应的数据。
str1 = 'abcdefg' # abcdefg
print(str1)
# 数据在程序运行过程中存储在内存中
# 使用字符串中某个特定的数据
# 这些字符数据从0开始顺序分配一个编号,叫下标,索引,索引值
# str[下标]
print(str1[0], str1[1]) # a b
四、切片
切片的作用:得到一部分数据
语法:序列[开始位置下标:结束位置下标:步长]
注意:
1、区域范围,包括左侧开始位置下标,不包括右侧结束位置下标,即[ )。
2、步长是选取间隔,正父整数都可以,默认步长是1
# 最常规代码
str2 = '012345' # 012345
print(str2[0:2:1]) # 01
print(str2[2:5:2]) # 24
print(str2[2:5]) # 234
# 进阶版
# 若是开始位置没写,默认从下标为0开始
str2 = '012345' # 012345
print(str2[:5]) # 01234
# 若是结束位置没写,默认到下标结束位置
print(str2[2:]) # 2345
# 若是开始、结束位置没写,表示选取所有
print(str2[:]) # 012345
# 若步长为负数,倒序排列
str3 = '012345' # 012345
print(str3[::-1]) # 543210
# 若开始写负数,下标-1代表最后一个数据,依次向前推
print(str3[-0]) # 0
print(str3[-1]) # 5
print(str3[-4]) # 2
print(str3[-4:-1]) # 234
# 若是开始、结束为负,步长为1
print(str3[-4:-1:1]) # 234
print(str3[-4:-1:-1]) # 没有数据,两个方向冲突,开始到结束,从左往右;步长从右往左
print(str3[-1:-4:-1]) # 543,两个方向一致,包括开始不包括结束
五、常用的操作方法
字符串的常用操作方法有:查找、修改、判断三大类,对于不常用的,用到的时候查找即可!
- 记函数的名字、记函数的作用、记住函数参数的传递方式
第一种查找
1、概念
查找子串在字符串中的位置或出现的次数
2、函数find()、index()、count()
- find()和index():检测某个子串是否包含在这个字符串中,如果在,返回这个子串开始的位置下标,否则返回-1
- count()计算子串在原来字符串中出现的个数
3、语法3个参数
1、字符串序列.find(子串,开始位置下标,结束位置的下标)值为要查找子串的位置下标,若是没有,返回-1
2、字符串序列.index(子串,开始位置下标,结束位置的下标)值为要查找子串的位置下标,若是没有,直接报错
3、字符串序列.count(子串,开始位置下标,结束位置的下标) 值为子串出现的个数
备注:若是不写开始、结束位置下标,代表从整个字符串查找
4、快速代码学习
'''
查找:
1、查找子串下标find()、index()
2、查找子串出现的次数count()
'''
# 1、find()
mystr = 'hello world and itcast and itheima and Python'
print(mystr.find('and')) # 12,因为下标从0开始,9+2=11,and的a开始字符的下标是12
print(mystr.find('and', 15, 30)) # 23
print(mystr.find('ands', 15, 30)) # -1
print(mystr[12:15]) # and (切片,选取部分子串)
# 2、index()
mystr1 = 'hello world and itcast and itheima and Python'
print(mystr1.index('and')) # 12
print(mystr1.index('and', 15, 30)) # 23
# print(mystr1.index('ands', 15, 30)) # 报错,ValueError: substring not found
print(mystr1[12:15]) # and (切片,选取部分子串)
# 3、count()
print(mystr.count('and', 15, 30)) # 1 代表此区间有1个and
print(mystr.count('and')) # 3 代表此区间有3个and
print(mystr.count('ands')) # 0 此区间没有ands
拓展:
rfind():和find()功能相同,下标从左边开始计算,查找方向为右侧开始
rindex():和index()功能相同,下标从左边开始计算,查找方向为右侧开始
# 4、rfind(),下标也是从左边计数,但是查找方向是从右往左,
print(mystr.rfind('and')) # 35
print(mystr.rfind('ands')) # -1
# 5、rindex(),同rfind()
print(mystr.rindex('and')) # 35
print(mystr.rindex('ands')) # 报错,ValueError: substring not found
index和rindex报错一样
第二种修改
1、概念
通过函数的形式修改字符串中的数据
2、函数
replace():替换
字符串序列.replace(旧子串,新子串,替换次数)
split():按照指定字符分割字符串
字符串序列.split(分割字符,num)
join():用一个字符或子串合并字符串,即将多个字符串合并为一个新的字符串
字符或子串.join(多字符串组成的序列)
大小写转换…
3、replce()语法
字符串序列.replace(旧子串,新子串,替换次数)
注意:若是替换次数不写,则替换掉所有
# 直接进行全部替换
# 1、replace()把and替换成he,replace有返回值(修改后的字符串),需要新的变量去接收
mystr = 'hello world and itcast and itheima and Python'
new_str = mystr.replace('and', 'he')
print(mystr)
# hello world and itcast and itheima and Python
print(new_str)
# hello world he itcast he itheima he Python
# 说明字符串是不可以数据类型
# 若是只进行1次替换,从左边开始替换
print(mystr.replace('and','or',1))
# hello world or itcast and itheima and Python
# 若是进行and的9次替换,超过原有的3个and,则会全部替换
print(mystr.replace('and','or',9))
#hello world or itcast or itheima or Python
4、 split()语法
语法:字符串.split(‘分隔符(也就是一个指定子串,进行前后分割)’)
# 2、split()--分割,返回一个列表,丢失分割字符,这里指and
mystr2 = 'hello world and itcast and itheima and Python'
print(type(mystr2.split('and')))
# <class 'list'>
list = mystr2.split('and')
print(list)
# ['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr2.split('and')) # 分割全部
# ['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr2.split('and', 2)) # 分割2次
# ['hello world ', ' itcast ', ' itheima and Python']
print(mystr2.split('and', 5)) # 超过3次
# ['hello world ', ' itcast ', ' itheima ', ' Python']
5、join()语法合并
合并列表中的字符串为一个大字符串
语法:’’.join(原字符串名称)
# 3、join()合并列表中的字符串为一个大字符串
mystr =[ 'hello','world','and ','itcast','and']
print('!'.join(mystr)) # hello!world!and !itcast!and
mystr3 = ['aa','bb','cc']
print('..'.join(mystr3)) # aa..bb..cc
mystr3 = ['aa','bb','cc']
new_str3 = '..'.join(mystr3)
print(new_str3) # aa..bb..cc
总结:仅限于字符串,所以的修改都可以用变量去接收
6、capitalize()语法将字符串第一个字符转大写
将字符串第一个字符转换成大写
# capitalize():将字符串第一个字符转换成大写
mystr = "hello world"
print(mystr.capitalize()) # Hello world
mystr = 'hello world'
print(mystr.capitalize()) # Hello world
7、title()语法将每个字母首字母转大写
将字符串每个单词首字母转换成大写
mystr = "hello world"
print(mystr.title()) # Hello World
mystr1='hello world'
print(mystr1.title()) # Hello World
8、lower()语法将字符串中的所有大写转小写
mystr = "HeLLo world"
print(mystr.lower()) # hello world
9、upper()语法将字符串中的小写转大写
mystr = "HeLLo world"
print(mystr.upper()) # HELLO WORLD
10、lstrip();rstrip;tripe(),删除字符串的空白字符
删除左边lstrip();删除右边rstrip;删除两侧tripe()
# 5、lstrip()删除字符串左侧空白字符
mystr = " HeLLo world"
new_str=mystr.lstrip()
print(new_str) # HeLLo world
# 6、rstrip()删除字符串右侧空白字符
mystr2 = "HeLLo world "
new_str2=mystr2.rstrip()
print(new_str2) # HeLLo world
# 7、strip()删除字符串两侧空白字符
mystr3 = " HeLLo world "
new_str3=mystr3.strip()
print(new_str3) # HeLLo world
11、左对齐ljust();右对齐rjust() ;中间对齐center()
字符串对齐ljust()左对齐;rjust() 右对齐;center()中间对齐,其它字符填充,或者空白都可,按照自己需求
# 8、ljust()字符串左对齐,右侧以1填充
mystr4 = 'hello'
print(mystr4.ljust(10,'1'))
# hello11111
# 9、rjust()字符串右对齐,左侧以2填充
print(mystr4.rjust(10,'2'))
# 22222hello
# 10、center()字符串居中,左右两侧以1填充
print(mystr4.center(10,'1'))
# 11hello111
# 注意:填充字符,看自己需求即可!
# 字符串序列.ljust/rjust/center(长度,'填充字符')
补充:
mystr = "HeLLo world"
# 输出
print(f'lower()的结果是:{mystr.lower()}')
print('lower()的结果是:', mystr.lower())
print('lower()的结果是:%s' % mystr.lower())
# lower()的结果是:hello world
# lower()的结果是: hello world
# lower()的结果是:hello world
第三种判断
1、概念
判断真假,返回的结果是布尔型数据类型,True和False
2、函数
一、判断字符串开头和结尾
startswith()和endswith()
3、startswith()
检查字符串是否以指定子串开头,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。没有指定,则是原字符串全部范围内检查
语法:字符串序列.startswith(子串,开始位置下标,结束位置下标)
mystr = "hello world"
print(mystr.startswith('hello')) # True
print(mystr.startswith('hell')) # True
print(mystr.startswith('hells')) # False
# 总结:判断子串是否这个开始、终止的范围内,若是,则返回True;否则返回False
# startswith(),范围是[ )
4、endswith()
检查字符串是否以指定子串结尾,是则返回True,否则返回False。
# 二、endswith()
mystr2 = "hello world"
print('endswith()')
print(mystr2.endswith('world')) # True
print(mystr2.endswith('worlds')) # False
print(mystr2.endswith('wor')) # False
print(mystr2.endswith('wor')) # False
总结:endswith()必须以指定的结尾,startswith()有指定的子串的至少有最前面一部分,例如hello的hell,hel,he都会判断为True
5、判断的其它函数
二、判断的其它函数
3、isalpha()
4、isdigit()判断字符串是否都是数字,若是返回True,否则False
5、isalnum()判断字母或数字或组合,若是返回True,若有空格或其它返回False
6、isspace()判断是否为空格,若全是,True;否则False
# 3、isalpha()判断是否都为字母,若都是返回True,有空格或其它,返回False
mystr = "hello world"
mystr2 = "helloboy"
print(mystr.isalpha()) # False
print(mystr2.isalpha()) # True
# 4、isdigit()判断是否都为数字,若都是返回True,有其它,返回False
mystr = "hello123"
mystr2 = '1234'
print(mystr.isdigit()) # False
print(mystr2.isdigit()) # True
# 5、isalnum()判断是否是字母或数字或组合,有任一返回True,若有其它,如空格,返回False
print(mystr.isalnum()) # True
mystr5 = '123 sss'
print(mystr5.isalnum()) # False,因为有空格
# 6、isspace()判断字符串是否都为空
mystr6 = ' '
print('空白:', mystr6.isspace())
六、字符串的总结
- 下标:下标又叫索引,作用是:通过下标可以快速找到对应的数据。
- 切片
语法:序列[开始位置下标:结束位置下标:步长]
- 常用的操作方法
- 查找
查找:
1、查找子串下标find()、index()
2、查找子串出现的次数count()
3、rfind()和rindex()查找方向是从右往左,下标也是从左边开始的
- 修改
一、常用修改方式:
1、replace(旧字符串,新字符串,替换次数)
2、split(分割字符,分割的次数num)
3、‘连接符号’.join(字符串)合并列表中的字符串为一个大字符串,…/也可以用空格,按照自己需要
二、字符串大小写转换
1、capitalize() 2、title() 3、lower() 4、upper()
三、字符串删除空白字符
5、lstrip() 6、rstrip() 7、strip()
四、字符串对齐
8、ljust()9、rjust() 10、center()
- 判断
一、判断开头或结尾
两种:1、startswith()和2、endswith()
二、判断的其它函数
3、isalpha()判断字符串是否都是字母,若是返回True,否则False
4、isdigit()判断字符串是否都是数字,若是返回True,否则False
5、isalnum()判断字母或数字或组合,若是返回True,若有空格或其它返回False
6、isspace()判断是否为空格,若全是,True;否则False