Python基础操作(二)(新手必看)超详细 (字符串操作专题)

字符串操作

字符串
字符串就是由单引号或双引号或者三引号包裹起来的

name = 'zhangsan'
name = "zhangsan"
name = """zhangsan"""
print(name)

**注意:**如果三引号没有变量接收,那么是注释,如果有变量接收,则为字符串
只要被单引号或双引号或者三引号包裹起来的内容都是字符串

字符串属于不可变类型
不可变类型:字符串中的内容一旦被定义,则无法进行更改
字符串不可于数字相加

字符串是一个有序的序列,字符串中的字符是有序排列的,根据索引(下标)进行排列

索引都是从0开始,到字符串的 长度-1 结束

word = 'hello'
# h  e  l  l  o
# 0  1  2  3  4  #正索引
#-5 -4 -3 -2 -1  #负索引

字符串是可以通过索引来进行取值的,有正数负数区分
格式:字符串[索引值]

word='hello'
print(word[3])  # 得到第二个l
print(word[4])  # 得到o
print(word[-1])  # 得到o
print(word[-2])  # 得到第二个l

字符串的切片操作
字符串的切片指的是:从字符串中复制一份指定的内容,存储在另一个变量中,不会对原字符串进行修改

切片格式:[起始索引:终止索引:步长]

参数:

起始索引:从哪一个索引位置开始进行切片操作,默认是0
终止索引:切片结束位置,默认是字符串的长度
步长:默认是1,步长的正负可以理解成坐标轴的正负方向
切片区间:[起始索引,结束索引)
word = 'hello world'
# 使用切片获取整个的字符串
w1 = word[::]  # w1 = word[:]也可
print(w1)
word = 'hello world'
w2 = word[2:-1:]
print(w2)   # llo worl
# h  e  l  l  o     w  o  r  l  d  # 字符
# 0  1  2  3  4  5  6  7  8  9  10   # 正索引
#-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1   # 负索引
word = 'hello world'
w3 = word[-1:2:]
print(w3)  # 什么都没有
w4 = word[-1:2:-1]
print(w4)  # dlrow ol

练习:
想要倒叙输出一个字符串
将python输出成 —> nohtyp

word = 'python'
A.word[-1:0:-1]  # nohty  
B.word[::-1]     # nohtyp
C.word[-1::-1]   # nohtyp
D.word[-1:-7:-1] # nohtyp

正确答案:BCD

遍历字符串(原因:字符串为可迭代对象)

两种方法:

word = 'python'

遍历word每一个字符
第一种:

for i in word:
     print(i)  # python

第二种:
**len()方法:**查看字符串的长度

len(word)  # 查看字符串长度
# range(0,end,1)
for i in range(6):
    print(word[i])  # python
for i in range(len(word)):
    print(word[i])   # python

字符串的拼接
字符串支持使用’+‘和’*'进行拼接

+:仅适用于字符串和字符串之间相加,不可以和其他数据类型相加
*:相当于字符串的连续拼接,乘几打印几次
first_name = 'qing'
last_name = 'ran'
full_name = first_name + last_name
print(full_name)  # qingran
print(full_name*3)  # qingranqingranqingran
full_name = first_name + ' ' + last_name # qing ran
full_name = first_name + '\n' + last_name # qing\nran

字符串方法(函数)
1.字符串的查找方法

find_str = 'hello world'

1.1 find() 查找:从左向右的查找,返回值是查找到的第一个元素的索引值

如果要查找的元素在字符串中,会返回第一个查找到的值,如果不存在,返回-1,不会报错

find()可以传三个参数,第一个参数是要查询的字符,第二个参数和第三个参数传索引值(确定查找范围)

res1 = find_str.find('h')
print(res1)  # 0
res2 = find_str.find('r')
print(res2)  # 8
res3 = find_str.find('l')
print(res3)  # 2
res4 = find_str.find('x')
print(res4)  # -1
res5 = find_str.find('l',3,5)
print(res5)  # 3

1.2 rfind() 查找从右向左查找,其余都和find方法相同
如果要查找的元素在字符串中,会返回第一个查找到的值,如果不存在,返回-1,不会报错

rfind_str = 'hello world'
res = rfind_str.rfind('l')
print(res)  # 9

1.3 index 查找:从左向右查找,返回值是查找到的第一个元素的索引值
如果找到元素,返回索引值
如果找不到元素,报错,不返回-1

index_str = 'hello world'
res = index_str.index('e')
print(res) # 1
res1 = index_str.index('l')
print(res1) # 2
res2 = index_str.index('x')
print(res2) # 报错
res3 = index_str.index('l',5,10)
print(res3) # 9

1.4 rindex() 查找从右向左查找,其余和index都一样

2.字符串的切割(拆分)方法
2.1 split() 切割:按照指定的内容进行切割
返回值是一个列表,([切割字符串前,切割字符串后])
如果切割的字符在字符串中出现多次,默认全部切割
可以使用maxsplit参数,指定切割次数
如果切割的字符不存在,不会进行切割,会将原字符串放到一个列表中

split_str = 'hello world'
res1 = split_str.split(' ')
print(res1) # ['hello', 'world'](列表)
res2 = split_str.split('l')
print(res2) # ['he', '', 'o wor', 'd'](列表)
    # 第一刀:['he','o world']
    # 第二刀:['he','','o world']
    # 第三刀:['he','','o wor','d']
res3 = split_str.split('l',maxsplit=1)
print(res3)  # ['he', 'lo world']
res4 = split_str.split('x')
print(res4)  # ['hello world']
**爬虫命名**
img_url = 'https://www.doutula.com/photo/8248929'
res5 = img_url.split('/')
print(res5)  # ['https:', '', 'www.doutula.com', 'photo', '8248929']
res5 = img_url.split('/')[-1]
print(res5) # 8248929

2.2 partition() 切割
返回的是元组,切割成三部分,(切割字符串前,切割字符串,切割字符串后)
如果切割的字符在原字符串中存在多个,那么会以第一个字符进行切割,不会全切

partition_str = 'hello world'
res1 = partition_str.partition('r')
print(res1)  # ('hello wo', 'r', 'ld')
res2 = partition_str.partition('l')
print(res2)  # ('he', 'l', 'lo world')
res3 = partition_str.partition('x')
print(res3)  # ('hello world', '', '')

3.字符串的统计方法
count() 统计、计数
返回值是被统计的元素在字符串中出现的次数下,如果不存在,返回0

count_str = 'hello world'
res1 = count_str.count('o')
print(res1)  # 2
res2 = count_str.count('l')
print(res2)  # 3
res3 = count_str.count('ll')
print(res3)  # 1
res4 = count_str.count('')
print(res4)  # 0

4.字符串的替换方法
replace() 替换
至少要传两个参数
参数:
replace(‘被替换字符’,‘替换成为的字符’,[替换次数])
返回值是替换后的字符
如果被替换的字符存在多个,会全部替换掉

replace_str = 'hello world'
res1 = replace_str.replace('w','v')
print(res1)  # hello vorld
res2 = replace_str.replace('l','x')
print(res2)  # hexxo worxd
res3 = replace_str.replace('l','x',1)
print(res3)  # hexlo world
replace_str = 'hello world'

将e替换成b,将w替换成Q
使用链式编程
注意:链式编程需要符合以下两点:

1.使用链式编程,第一个方法必须要有返回值
2.每一个使用的方法的返回值必须能够调用下一个方法
res1 = replace_str.replace('e','b')
res2 = res1.replace('w','Q')
print(res2)  # hbllo Qorld
链式编程:
res1 = replace_str.replace('e','b').replace('w','Q')
print(res1)  # hbllo Qorld

5.字符串的修饰方法
5.1 strip()
去除字符串两端的指定字符(默认去除空白字符),中间的不能去掉

strip_str = '   hello world      '
res1 = strip_str.strip()
print(res1)  # hello world
strip_str = '~~~~hello world~'
res2 = strip_str.strip('~')
print(res2)  # hello world

5.2 lstrip() 只去除左端的指定字符,其余和strip()方法一样
5.3 rstrip() 只去除右端的指定字符,其余和strip()方法一样

5.4 center() 使字符串居中显示
参数:
第一个参数:字符串的长度(填充后的字符串长度)
如果字符串填充的长度不能够让字符串居中显示,左短右长

center_str = 'hello'
res1 = center_str.center(11)
print(res1)  # |   hello   |
res2 = center_str.center(8)
print(res2)  # | hello  |

第二个参数:是填充字符,默认是空格(’ ')
可以指定字符进行填充,会在字符串左右两端进行填充

center_str = 'hello'
res1 = center_str.center(11,'*')
print(res1)  # ***hello***

5.5 ljust() 居左显示,其余和center()一致
5.6 rjust() 居右显示,其余和center()一致

6.字符串的格式化方法
format() 关键是{}
6.1 使用位置参数:一个萝卜一个坑,不能够换顺序

message = '我是{},今年{}了,性别{},身高{}cm'
res1 = message.format('zhangsan',20,'man',150)
print(res1)  # 我是zhangsan,今年20了,性别man,身高150cm
res2 = message.format('man',150,'zhangsan',20)
print(res2)  # 我是man,今年150了,性别zhangsan,身高20cm

6.2 使用关键字参数

message = '我是{name},今年{age}了,性别{sex},身高{height}cm'
res1 = message.format(name = 'zhangsan',age = 20,sex = 'man',height = 150)
print(res1)  # 我是zhangsan,今年20了,性别man,身高150cm
res2 = message.format(height = 150,age = 20,sex = 'man',name = 'zhangsan')
print(res2)  # 我是zhangsan,今年20了,性别man,身高150cm

6.3 使用位置参数(索引)

message = '我是{0},今年{1}了,性别{2},身高{3}cm'
res1 = message.format('zhangsan',20,'man',150)
print(res1)  # 我是zhangsan,今年20了,性别man,身高150cm
message = '我是{1},今年{0}了,性别{3},身高{2}cm'
res2 = message.format(20,'zhangsan',150,'man')
print(res2)  # 我是zhangsan,今年20了,性别man,身高150cm

7.字符串的变形方法
7.1 upper() 将字符串中所有的字母转换成大写

upper_str = 'hello'
res = upper_str.upper()
print(res)  # HELLO

7.2 lower() 将字符串中的所有字母转换成小写

lower_str = 'HELLO'
res = lower_str.lower()
print(res)  # hello

7.3 swapcase() 大小写转换

swapcase_str = 'HeLLo'
res = swapcase_str.swapcase()
print(res)  # hEllO

7.4 title() 将字符串的英文单词首字母转换成大写
注:单词是根据非字母进行区分

title_str = 'hello world'
res = title_str.title()
print(res)  # Hello World
title_str = 'helloworld'
res1 = title_str.title()
print(res1)  # Helloworld
title_str = 'hello6world'
res2 = title_str.title()
print(res2)  # Hello6World

7.5 capitalize() 将字符串的首字母转换成大写

capitalize_str = 'hello world'
res = capitalize_str.capitalize()
print(res)  # Hello world

8.字符串的判断方法
8.1 isalnum() 判断字符串是否全部由字母或数字组成
判断三类:全部是字母、全部是数字、数字+字母,返回布尔值

isalnum_str = '123456'
res1 = isalnum_str.isalnum()
print(res1)  # True

8.2 isalpha() 判断字符串是否全部由字母组成
8.3 isdigit() 判断字符串是否全部由数字组成
8.4 isupper() 判断字符串是否全部是大写的/是否符合upper()
8.5 islower() 判断字符串是否全部是小写的/是否符合lower()
8.6 istitle() 判断字符串是否满足title的格式

8.7 startswith() 判断字符串是否以……开头

startswith_str = 'hello'
res1 = startswith_str.startswith('h')
print(res1)  # True
res2 = startswith_str.startswith('o')
print(res2)  # False
res3 = startswith_str.startswith('he')
print(res3)  # True

8.8 endswith() 判断字符串是否以……结尾

endswith_str = 'hello'
res = endswith_str.endswith('o')
print(res)  # True
res1 = endswith_str.endswith('ol')
print(res1)  # False

9.使用字符串需要注意:

单引号里面不能再有单引号,双引号里面不能再有双引号
单引号里面可以有双引号,双引号里面可以有单引号
如果就是想重复包含,必须使用\,对引号进行转义
message = 'He said: 'today is a nice day''
print(message)  # 报错
message = 'He said: "today is a nice day"'
print(message)  # He said: "today is a nice day"
message = 'He said: \'today is a nice day\''
print(message)  # He said: 'today is a nice day'
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值