Python【字符串】【列表】【元组】常用操作

文章目录

    • 9.2字符串常见操作
      • 9.2.1 `find`
      • 9.2.2 `index`
      • 9.2.3 `count`
      • 9.2.4 `replace`
      • 9.2.5 `split`
      • 9.2.6 `capitalize`
      • 9.2.7 `title`
      • 9.2.8 `startswith`
      • 9.2.9 `endswith`
      • 9.2.10 `lower`
      • 9.2.11 `upper`
      • 9.2.12 `ljust`
      • 9.2.13 `rjust`
      • 9.2.14 `center`
      • 9.2.15 `lstrip`
      • 9.2.16 `rstrip`
      • 9.2.17 `strip`
      • 9.2.18 `rfind`
      • 9.2.19 `rindex`
      • 9.2.20 `partition`
      • 9.2.21 `rpartition`
      • 9.2.22 `splitlines`
      • 9.2.23 `isalpha`
      • 9.2.24 `isdigit`
      • 9.2.25 `isalnum`
      • 9.2.26 `isspace`
      • 9.2.27 `join`
    • 9.3 列表List
      • 9.3.1 for循环遍历list
      • 9.3.2 while循环遍历list
      • 9.4 列表的常用操作
      • 9.4.1 添加元素("增"append, extend, insert)
      • 9.4.2 修改元素(“改”)
      • 9.4.3 查找元素("查"in, not in, index, count)
      • 9.4.4 删除元素("删"del, pop, remove)
      • 9.4.5 排序(sort, reverse)
    • 9.5 元组
      • 9.5.1 访问元组
      • 9.5.2 修改元组
      • 9.5.3 元组的内置函数count, index
    • 9.6 字典
      • 9.6.1 根据键访问值
      • 9.7 字典的常用操作
      • 9.7.1 修改元素字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改,例:
      • 9.7.2 添加元素使用 变量名[‘键’] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素,例:
      • 9.7.3 删除元素对字典进行删除操作,有一下几种:
      • 9.7.4 字典的长度
      • 9.7.5 找出字典中的所有key
      • 9.7.6 找出字典所有的value
      • 9.7.7 找出字典的(键,值)
      • 9.7.8 判断key是否存在
      • 9.7.9 遍历字典的几种方式


9.2字符串常见操作

9.2.1 find

检测 str 是否包含在 mystr中,如果是返回开始的索引值,否则返回-1,语法:
mystr.find(str, start=0, end=len(mystr))

mystr = 'hello world! world'
print(mystr.find("ll", 0, len(mystr)))
2

9.2.2 index

跟find()方法一样,只不过如果str不在 mystr中会报一个异常,语法:
mystr.index(str, start=0, end=len(mystr))

mystr = 'hello world! world'
print(mystr.index("ll", 0, len(mystr)))
2

9.2.3 count

返回 str在start和end之间 在 mystr里面出现的次数,语法:
mystr.count(str, start=0, end=len(mystr))

mystr = 'hello world! world'
print(mystr.count("world", 0, len(mystr)))
2

9.2.4 replace

把 mystr 中的 str1 替换成 str2,如果 count 指定,则替换不超过 count 次,语法:
mystr.replace(str1, str2, mystr.count(str1))

mystr = 'hello world! world'
newStr=mystr.replace("world","Tom",mystr.count("world"))
print(newStr)
hello Tom! Tom

9.2.5 split

以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符语法:
mystr.split(str=" ", 2) '2’代表切几刀

mystr = 'hello world! world'
newStr=mystr.split(" ",2)
print(newStr)
['hello', 'world!', 'world']

9.2.6 capitalize

把字符串的第一个字符大写,其他的变成小写,语法:
mystr.capitalize()

mystr = 'hello world world'
print(mystr.capitalize())
Hello world world

9.2.7 title

把字符串的每个单词首字母大写,其他的改成小写,例:

mystr = 'hello world world'
print(mystr.title())
Hello World World

9.2.8 startswith

检查字符串是否是以 obj 开头, 是则返回 True,否则返回 False
mystr.startswith(obj)

mystr = 'hello world world'
ss='hello'
print(mystr.startswith(ss)) #大小写敏感
True

9.2.9 endswith

检查字符串是否以obj结束,如果是返回True,否则返回 False,用法同上
mystr.endswith(obj)

mystr = 'hello world world'
ss='hello'
print(mystr.endswith(ss))
False

9.2.10 lower

转换 mystr 中所有大写字符为小写
mystr.lower()

mystr = 'HELLO WORLD WORLD'
print(mystr.lower())
hello world world

9.2.11 upper

转换 mystr 中的小写字母为大写,用法同上。
mystr.upper()

mystr = 'hello world world'
print(mystr.upper())
HELLO WORLD WORLD

9.2.12 ljust

返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
mystr.ljust(width)

mystr = "hello world"
print(mystr.rjust(20,"*"))
*********hello world

9.2.13 rjust

返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
mystr.rjust(width)

mystr = "hello world world"
print(mystr.rjust(30))
             hello world world

9.2.14 center

返回一个原字符串居中,并使用空格填充至长度 width 的新字符串,用法同上。
mystr.center(width)

mystr = "hello world world"
print(mystr.center(30))
      hello world world       

9.2.15 lstrip

删除 mystr 左边的空白字符
mystr.lstrip()

mystr = "     hello world world"
print(mystr. lstrip())
hello world world

9.2.16 rstrip

删除 mystr 字符串末尾的空白字符
mystr.rstrip()

mystr = "hello world world"
print(mystr. rstrip())
hello world world    *

9.2.17 strip

删除mystr字符串两端的空白字符

mystr = "       hello world world      "
print(mystr. strip())
hello world world

9.2.18 rfind

类似于 find()函数,不过是从右边开始查找.
mystr.rfind(str, start=0,end=len(mystr) )

mystr = "hello world world"
print(mystr.rfind("h",0,len(mystr)))
0

9.2.19 rindex

类似于 index(),不过是从右边开始.
mystr.rindex( str, start=0,end=len(mystr))

mystr = "hello world world"
print(mystr.rindex("h",0,len(mystr)))
0

9.2.20 partition

把mystr以str分割成三部分,str前,str和str后
mystr.partition(str)

mystr = "helloworldworld"
print(mystr.partition("ld"))
('hellowor', 'ld', 'world')

9.2.21 rpartition

类似于 partition()函数,不过是从右边开始.
mystr.rpartition(str)

mystr = "helloworldworld"
print(mystr.rpartition("ld"))
('helloworldwor', 'ld', '')

9.2.22 splitlines

按照行分隔,返回一个包含各行作为元素的列表
mystr.splitlines()

mystr = "hello\nworld\nworld"
print(mystr.splitlines())
['hello', 'world', 'world']

9.2.23 isalpha

如果 mystr 所有字符都是字母 则返回 True,否则返回 False
mystr.isalpha()

mystr = "helloworldworld"
mystr_2 = "hello6666666"
mystr_3 = "hello world world"
print(mystr.isalpha())
print(mystr_2.isalpha())
print(mystr_3.isalpha())
True
False
False

9.2.24 isdigit

如果 mystr 只包含数字则返回 True 否则返回 False.
mystr.isdigit()

mystr = "helloworldworld"
mystr_2 = "6666666"
mystr_3 = "hello world world"
print(mystr.isdigit())
print(mystr_2.isdigit())
print(mystr_3.isdigit())
False
True
False

9.2.25 isalnum

如果 mystr 所有字符都是字母或数字则返回 True,否则返回 False
mystr.isalnum()

mystr = "hello world world"
mystr_2 ="hello123456"
mystr_3 ="hello 123456"
print(mystr.isalnum())
print(mystr_2.isalnum())
print(mystr_3.isalnum())
False
True
False

9.2.26 isspace

如果 mystr 中只包含空格,则返回 True,否则返回 False.
mystr.isspace()

mystr ="    "
mystr_2 ="hello world world"
print(mystr.isspace())
print(mystr_2.isspace())
True
False

9.2.27 join

作用:连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串。
语法:’ sep ’ . join( seq )
参数说明:
sep:分隔符,可以为空。
seq:要连接的元素序列、字符串、元组、字典。
上面的语法即:以sep作为分隔符,将seq所有的元素合并成一个新的字符串。
返回值:返回一个以分隔符sep连接各个元素后生成的字符串。

seq1 = ['hello','good','boy','doiido']
print(seq1)
print (' '.join(seq1))
print (':'.join(seq1))
['hello', 'good', 'boy', 'doiido']
hello good boy doiido
hello:good:boy:doiido

9.3 列表List

列表list用[,…]表示,格式如下:
namesList = ['xiaoWang','xiaoZhang','xiaoHua']

9.3.1 for循环遍历list

namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']
for name in namesList:
    print(name)
xiaoWang
xiaoZhang
xiaoHua

列表推导式1)普通方式

a = [x for x in range(4)]
print(a)
b = [x for x in range(3, 4)]
print(b)
c = [x for x in range(3, 19)]
print(c)
d = [x for x in range(3, 19, 2)]
print(d)
[0, 1, 2, 3]
[3]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
[3, 5, 7, 9, 11, 13, 15, 17]

2)在循环的过程中加入if判断

a = [x for x in range(3, 15) if x % 2 == 0]
print(a)
b = [x for x in range(3, 15) if x % 2 != 0]
print(b)
b = [x for x in range(3, 15)]
print(b)
[4, 6, 8, 10, 12, 14]
[3, 5, 7, 9, 11, 13]
[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

3)多个for循环

a = [(x, y) for x in range(3, 5) for y in range(3)]
print(a)
b = [(x, y, z) for x in range(3, 5) for y in range(3) for z in range(4, 6)]
print(b)
[(3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2)]
[(3, 0, 4), (3, 0, 5), (3, 1, 4), (3, 1, 5), (3, 2, 4), (3, 2, 5), (4, 0, 4), (4, 0, 5), (4, 1, 4), (4, 1, 5), (4, 2, 4), (4, 2, 5)]

9.3.2 while循环遍历list

namesList = ['xiaoWang', 'xiaoZhang', 'xiaoHua']
length = len(namesList)
i = 0
while i < length:
    print(namesList[i])
    i += 1
xiaoWang
xiaoZhang
xiaoHua

9.4 列表的常用操作

列表中存放的数据是可以进行修改的,比如"增"、“删”、“改”"

9.4.1 添加元素("增"append, extend, insert)

append:通过append可以向列表添加元素

#定义变量A,默认有3个元素
A = ['xiaoWang','xiaoZhang','xiaoHua']
print("-----添加之前,列表A的数据-----")
for tempName in A:
    print(tempName)

#提示、并添加元素
temp = input('请输入姓名:')
A.append(temp)

print("-----添加之后,列表A的数据-----")
for tempName in A:
    print(tempName)
-----添加之前,列表A的数据-----
xiaoWang
xiaoZhang
xiaoHua
-----添加之后,列表A的数据-----
xiaoWang
xiaoZhang
xiaoHua
QWER

extend:通过extend可以将另一个集合中的元素逐一添加到列表中

a = [1, 2]
b = [3, 4]
a.append(b)
print(a)
a.extend(b)
print(a)
[1, 2, [3, 4]]
[1, 2, [3, 4], 3, 4]

insert :insert(index, object) 在指定位置index前插入元素object

a = [0, 1, 2]
a.insert(1, 3)
print(a)
[0, 3, 1, 2]

9.4.2 修改元素(“改”)

修改元素的时候,要通过下标来确定要修改的是哪个元素,然后才能进行修改,例:

#定义变量A,默认有3个元素
A = ['xiaoWang','xiaoZhang','xiaoHua']

print("-----修改之前,列表A的数据-----")
for tempName in A:
    print(tempName)

#修改元素
A[1] = 'xiaoLu'
print("-----修改之后,列表A的数据-----")
for tempName in A:
    print(tempName)
-----修改之前,列表A的数据-----
xiaoWang
xiaoZhang
xiaoHua
-----修改之后,列表A的数据-----
xiaoWang
xiaoLu
xiaoHua

9.4.3 查找元素("查"in, not in, index, count)

所谓的查找,就是看看指定的元素是否存在

in, not in

python中查找的常用方法为:

in(存在),如果存在那么结果为true,否则为false
not in(不存在),如果不存在那么结果为true,否则false

#待查找的列表
nameList = ['xiaoWang','xiaoZhang','xiaoHua']
#获取用户要查找的名字
findName = input('请输入要查找的姓名:')
#查找是否存在
if findName in nameList:
    print('在字典中找到了相同的名字')
else:
    print('没有找到')
#in的方法只要会用了,那么not in也是同样的用法,只不过not in判断的是不存在
在字典中找到了相同的名字

index, count

index和count与字符串中的用法相同

a = ['a', 'b', 'c', 'a', 'b']
print(a.index('a', 1, 4))
print(a.count('b'))
print(a.count('d'))
print(a.index('a', 1, 3)) # 注意是左闭右开区间
3
2
0



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

 in 
      3 print(a.count('b'))
      4 print(a.count('d'))
----> 5 print(a.index('a', 1, 3)) # 注意是左闭右开区间


ValueError: 'a' is not in list

9.4.4 删除元素("删"del, pop, remove)

类比现实生活中,如果某位同学调班了,那么就应该把这个条走后的学生的姓名删除掉;在开发中经常会用到删除这种功能。

列表元素的常用删除方法有:

del:根据下标进行删除
pop:删除最后一个元素
remove:根据元素的值进行删除

#例:(pop)
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']
print('------删除之前------')
for tempName in movieName:
    print(tempName)
del movieName[2]
print('------删除之后------')
for tempName in movieName:
    print(tempName)
------删除之前------
加勒比海盗
骇客帝国
第一滴血
指环王
霍比特人
速度与激情
------删除之后------
加勒比海盗
骇客帝国
指环王
霍比特人
速度与激情
#例:(remove)
movieName = ['加勒比海盗','骇客帝国','第一滴血','指环王','霍比特人','速度与激情']

print('------删除之前------')
for tempName in movieName:
    print(tempName)

movieName.remove('指环王')

print('------删除之后------')
for tempName in movieName:
    print(tempName)
------删除之前------
加勒比海盗
骇客帝国
第一滴血
指环王
霍比特人
速度与激情
------删除之后------
加勒比海盗
骇客帝国
第一滴血
霍比特人
速度与激情

9.4.5 排序(sort, reverse)

sort方法是将list按特定顺序重新排列,默认为由小到大,参数reverse=True可改为倒序,由大到小。

reverse方法是将list逆置。

a = [1, 4, 2, 3]
a.reverse()
print(a)
a.sort()
print(a)
a.sort(reverse=True)
print(a)
[3, 2, 4, 1]
[1, 2, 3, 4]
[4, 3, 2, 1]

9.5 元组

Python的元组与列表类似,不同之处在于元组的元素不能修改。元组使用小括号(),列表使用方括号[],例:

aTuple = ('et',77,99.9)
print(aTuple)
('et', 77, 99.9)

9.5.1 访问元组

aTuple = ('et',77,99.9)
print(aTuple[0])
print(aTuple[1])
et
77

9.5.2 修改元组

aTuple = ('et',77,99.9)
aTuple[0]=111
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 aTuple = ('et',77,99.9)
----> 2 aTuple[0]=111


TypeError: 'tuple' object does not support item assignment

从上面的运行结果可以得出: python中不允许修改元组的数据,包括不能删除其中的元素。

9.5.3 元组的内置函数count, index

index和count与字符串和列表中的用法相同

a = ('a', 'b', 'c', 'a', 'b')
a.index('a', 1, 3) # 注意是左闭右开区间
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

 in 
      1 a = ('a', 'b', 'c', 'a', 'b')
----> 2 a.index('a', 1, 3) # 注意是左闭右开区间
      3 a.index('a', 1, 4)
      4 a.count('b')
      5 a.count('d')


ValueError: tuple.index(x): x not in tuple
a.index('a', 1, 4)
a.count('b')
a.count('d')
0

9.6 字典

字典是一种可变容器模型,且可存储任意类型对象。

字典的每个键值 key=>value 对用冒号 : 分割,每个对之间用逗号(,)分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2, key3 : value3 }

9.6.1 根据键访问值

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
print(info['name'])
print(info['address'])
学姐
中国上海

若访问不存在的键,则会报错在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法,还可以设置默认值:

age = info.get('age')
age #'age'键不存在,所以age为None
type(age)
NoneType
age = info.get('age', 18) # 若info中不存在'age'这个键,就返回默认值18
age
18

9.7 字典的常用操作

9.7.1 修改元素字典的每个元素中的数据是可以修改的,只要通过key找到,即可修改,例:

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
info['id'] = 88888
print('修改之后的id为:%d' % info['id'])
修改之后的id为:88888

9.7.2 添加元素使用 变量名[‘键’] = 数据 时,这个“键”在字典中,不存在,那么就会新增这个元素,例:

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
newId = input('请输入新的ID')
info['id'] = int(newId)

print('添加之后的id为:%d' % info['id'])
print(info)
添加之后的id为:121212
{'name': '学姐', 'id': 121212, 'sex': 'f', 'address': '中国上海'}

9.7.3 删除元素对字典进行删除操作,有一下几种:

del
clear()

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
print('删除前,%s' % info['name'])
del info['name']
print('删除后,%s' % info['name'])
删除前,学姐

---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

 in 
      2 print('删除前,%s' % info['name'])
      3 del info['name']
----> 4 print('删除后,%s' % info['name'])


KeyError: 'name'

del删除整个字典

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
print('删除前,%s' % info)
del info
print('删除后,%s' % info)
删除前,{'name': '学姐', 'id': 99999, 'sex': 'f', 'address': '中国上海'}

---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

 in 
      2 print('删除前,%s' % info)
      3 del info
----> 4 print('删除后,%s' % info)


NameError: name 'info' is not defined

clear清空整个字典

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
print('清空前,%s' % info)
info.clear()
print('清空后,%s' % info)
清空前,{'name': '学姐', 'id': 99999, 'sex': 'f', 'address': '中国上海'}
清空后,{}

9.7.4 字典的长度

使用len()方法,求字典的长度,例:

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
print('字典的长度:%d' % len(info))
字典的长度:3

9.7.5 找出字典中的所有key

keys返回一个包含字典所有KEY的视图对象,例:

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
dicKeys=info.keys()
print(dicKeys)
print(dicKeys[0])
dict_keys(['name', 'id', 'sex', 'address'])

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      2 dicKeys=info.keys()
      3 print(dicKeys)
----> 4 print(dicKeys[0])


TypeError: 'dict_keys' object is not subscriptable

9.7.6 找出字典所有的value

属性values返回一个包含字典所有value的视图列表,用法同上,例:

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
dicvalues=list(info.values())
print(dicvalues)
print(dicvalues[0])
['学姐', 99999, 'f', '中国上海']
学姐

9.7.7 找出字典的(键,值)

属性items,返回一个包含所有(键,值)元祖的列表

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
dicItems=info.items()
print(dicItems)
dict_items([('name', '学姐'), ('id', 99999), ('sex', 'f'), ('address', '中国上海')])

9.7.8 判断key是否存在

“key in dict"如果键在字典dict里返回true,否则返回false,例:

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
ss='name' in info
print(ss)
True

9.7.9 遍历字典的几种方式

1) 遍历字典的key(键)

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
for key in info.keys():
    print(key)
name
id
sex
address

2) 遍历字典的value(值)

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
for key in info.values():
    print(key)
学姐
99999
f
中国上海

3) 遍历字典的项(元素)

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
for item in info.items():
    print(item)
('name', '学姐')
('id', 99999)
('sex', 'f')
('address', '中国上海')

4) 遍历字典的key-value(键值对)

info = {'name':'学姐', 'id':99999, 'sex':'f', 'address':'中国上海'}
for key, value in info.items():
    print("key=%s,value=%s" % (key, value))
key=name,value=学姐
key=id,value=99999
key=sex,value=f
key=address,value=中国上海

参考资料:爆肝六万字整理的python基础,快速入门python的首选

你可能感兴趣的:(Python常用库,python)