第六章 字符串对象和切片操作

目录

第六章 字符串对象和切片操作

6.1 字符串对象

6.2 字符中常用的方法

6.3 切片操作

第六章 字符串对象和切片操作

6.1 字符串对象

字符串:由多个字符组成的串

字符:肉眼所能看到的符号

字节:肉眼看不到的

python定义字符串的方式:

单引号 双引 三引号 str()

6.2 字符中常用的方法

 >>> dir(s)
 ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

capitalize ------- 将字符串中的首字母变成大写

 >>> s
 'this is a string'
 >>> s.capitalize()
 'This is a string'

center(width, fillchar=' ') ------ 将字符串按照给定的长度进行居中显示,居中对齐

rjust --------- 右对齐

ljust ------ 左对齐

 >>> help(s.center)
 Help on built-in function center:
 ​
 center(width, fillchar=' ', /) method of builtins.str instance
     Return a centered string of length width.
 ​
     Padding is done using the specified fill character (default is a space).
 ​
 >>> s.center(40)
 '            this is a string            '
 >>> s.center(40,"*")
 '************this is a string************'
 >>> s.rjust(40)
 '                        this is a string'
 >>> s.ljust(40)
 'this is a string                        '
 >>> s.ljust(40,"*")
 'this is a string************************'
 >>> s.rjust(40,"*")
 '************************this is a string'

count --------- 统计的字符在字符串中出现的次数

 >>> s
 'this is a string'
 >>> s.count("s")
 3
 >>> s.count("is")
 2

endswith ------- 判断字符串是不是以XXX结尾

startswith ------- 判断字符串是不是以XXX开头

 >>> s.endswith("g")
 True
 >>> s.endswith("ing")
 True
 >>> s.endswith("f")
 False
 >>> s.startswith("t")
 True
 >>> s.startswith("f")
 False

index ------ 查找的字符或者字符串在字符串中第一次出现的位置,如果不存在抛出异常(报错)

rindex -------从右往左找,查找的字符或者字符串在字符串中第一次出现的位置(相当于从左往右找的字符或者字符串在字符串中最后一次出现的位置),如果不存在抛出异常(报错)

 >>> s
 'this is a string'
 >>> s.index("s")
 3
 >>> s.index("is")
 2
 >>> s.index("f")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 ValueError: substring not found
 >>> s.index(" ")
 4
 >>> s.rindex("s")
 10
 >>> s.rindex("f")
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 ValueError: substring not found

find ------- 查找的字符或者字符串在字符串中第一次出现的位置,如果不存在返回-1

rfind----- 从右往左找,查找的字符或者字符串在字符串中第一次出现的位置(相当于从左往右找的字符或者字符串在字符串中最后一次出现的位置),如果不存在返回-1

 >>> s
 'this is a string'
 >>> s.find("s")
 3
 >>> s.find("f")
 -1
 >>> s.rfind("f")
 -1
 >>> s.rfind("s")
 10

encode ----- python3中 将字符串转换为字节的方法,decode() 将字节转换为字符串的方法(字节里的方法)

 >>> s
 'this is a string'
 >>> s.encode()
 b'this is a string'
 >>> d = s.encode()
 >>> d
 b'this is a string'
 >>> type(d)
 <class 'bytes'>
 >>> d
 b'this is a string'
 >>> d.decode()
 'this is a string'
 >>> ss = d.decode()
 >>> ss
 'this is a string'
 >>> type(ss)
 <class 'str'>

format ------ 格式化字符串,拼接字符串

isupper ------ 判断字符串是不是全部都是大写字母

islower ----- ------ 判断字符串是不是全部都是小写字母

>>> s.isupper()
False
>>> s.islower()
False

istitle ----- 判断是不是标题

>>> s.istitle()
False
>>> ss = "This Is A Dog"
>>> ss.istitle()
True

isspace ----- 判断是不是空格位 不太常用

>>> sss = "       "
>>> sss.isspace()
True
>>> ss
'This Is A Dog'
>>> ss.isspace()
False

isdigit ------ 判断是不是数字

>>> sss = "123234344"
>>> sss.isdigit()
True
>>> ss
'This Is A Dog'
>>> ss.isdigit()
False
>>> sss = "1233443gggg"
>>> sss.isdigit()
False

isalnum ------ 判断的是是不是字母和数字(alpha-numeric)

>>> help(s.isalnum)
Help on built-in function isalnum:

isalnum() method of builtins.str instance
    Return True if the string is an alpha-numeric string, False otherwise.

    A string is alpha-numeric if all characters in the string are alpha-numeric and
    there is at least one character in the string.

>>> sss
'1233443gggg'
>>> sss.isalnum()
True
>>> ss
'This Is A Dog'
>>> ss.isalnum()
False

isalpha ------ 判断的是不是字母

title ----- 将字符串转换为标题的格式

>>> s
'This is a string'
>>> s.istitle()
False
>>> s.title()
'This Is A String'
>>> sss = s.title()
>>> sss
'This Is A String'
>>> sss.istitle()
True

upper ------- 将字符串转换为大写

lower ------- 将字符串转换为小写

>>> s
'This is a string'
>>> s.lower()
'this is a string'
>>> s.upper()
'THIS IS A STRING'

split ----- 按照指定的符号将字符串进行切割,返回值是一个列表

>>> s
'This is a string'
>>> s.split(" ")
['This', 'is', 'a', 'string']
>>> l = s.split(" ")
>>> l
['This', 'is', 'a', 'string']
>>> type(l)
<class 'list'>
>>> l = s.split("s")
>>> l
['Thi', ' i', ' a ', 'tring']

join ------ 按照指定的格式将一个可迭代对象拼接成字符串

>>> ls = ["A","B","c","d"]
>>> type(ls)
<class 'list'>
>>> ss = " ".join(ls)
>>> ss
'A B c d'
>>> type(ss)
<class 'str'>
>>> ss = "*".join(ls)
>>> ss
'A*B*c*d'

strip ------- 清除两侧的空格

rstrip------ 清除右侧的空格

lstrip -------- 清除左侧空格

>>> ss = "                              hhhhhhh                                  "
>>> ss
'                              hhhhhhh                                  '
>>> ss.strip()
'hhhhhhh'
>>> ss.strip()
'hhhhhhh'
>>> ss
'                              hhhhhhh                                  '
>>> ss.rstrip()
'                              hhhhhhh'
>>> ss.lstrip()
'hhhhhhh                                  '

replace (“原字符”,"新字符") ------ 替换对应的字符

>>> s
'This is a string'
>>> s.replace("s","t")
'Thit it a ttring'

6.3 切片操作

切片:用来分隔可迭代对象(容器)

语法规则:

object[start_index:end_index:step]

start_index ------- 起始索引(起始的位置)

end_index ------ 结束索引(结束的位置),不包含end_index处的值

step ---- 步长,可以取正数也可以取负数,正数(从左往右)负数(从右往左),默认值是1

object[:]  ----- 切割的是一个完整的对象
object[start_index:]  ------ 从start_index开始切割到最后的位置,步长为1
object[:end_index] ------ 从最开始的位置切割到end_index处,但是不包含end_index
object[start_index:end_index] ------- 从start_index开始切割到end_index处,但是不包含end_index,步长为1
object[start_index:end_index:step] ------------ 从start_index开始切割到end_index处,但是不包含end_index,步长为step  

前闭后开的区间

ls = [0,1,2,3,4,5,6,7,8,9]

1、切割单个值

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[0]
0
>>> ls[-4]
6

2、切割完整的对象

>>> ls[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[::]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[::-1]  #-1 表示从右往左切割 所以是倒序
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

3、start_index和end_index均为正数

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[1:6]
[1, 2, 3, 4, 5]
>>> ls[1:6:-1]  # start_index=1 end_index = 6表示的是从1切割到6的位置,但是不包含6处的值,从左往右切割,step=-1 表示从右往左   
[]
>>> ls[6:1]
[]
>>> ls[6:1:-1]
[6, 5, 4, 3, 2]
>>> ls[:6]
[0, 1, 2, 3, 4, 5]
>>> ls[:6:-1]
[9, 8, 7]
>>> ls[6:]
[6, 7, 8, 9]
>>> ls[6::-1]
[6, 5, 4, 3, 2, 1, 0]
>>>

4、start_index和end_index均为负数

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[-1:-6]
[]
>>> ls[-1:-6:-1]
[9, 8, 7, 6, 5]
>>> ls[-6:-1]
[4, 5, 6, 7, 8]
>>> ls[:-6]
[0, 1, 2, 3]
>>> ls[:-6:-1]
[9, 8, 7, 6, 5]
>>> ls[-6:]
[4, 5, 6, 7, 8, 9]
>>> ls[-6::-1]
[4, 3, 2, 1, 0]

5、start_index和end_index正和负结合

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[1:-6]
[1, 2, 3]
>>> ls[1:-6:-1]
[]
>>> ls[-1:6]
[]
>>> ls[-1:6:-1]
[9, 8, 7]

6、连续切片

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[:8][2:5][-1:]
[4]
ls[:8] ----- [0,1,2,3,4,5,6,7]
ls[:8][2:5]   -----   [2,3,4]
ls[:8][2:5][-1:] ----- [4]

7、切片的三个参数也可以是表达式

>>> ls
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> ls[2+1:3*2:7%3]
[3, 4, 5]
>>> ls[3:6:1]
[3, 4, 5]
>>> ls[2:6:2]
[2, 4]

8、切片也可以切割其他的对象

>>> (1,2,3,4,5,6,7,8,9)[:3]
(1, 2, 3)
>>> "ABCDEFGHIJK"[::2]
'ACEGIK'
>>> for i in range(1,100)[2::3][-10:]:
...     print(i)
...
72
75
78
81
84
87
90
93
96
99

面试题:

1、如果使用切片切割数据的时候,超出了下标的范围,会不会报错?

不会报错,如果超出范围,会返回的是完整的对象,如果前后矛盾返回的是[]

2、在python中如何将列表进行反向输出?

循环反向

[::-1]

list.reverse()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

璀云霄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值