Python序列

字符串

  • 一对引号字符串

    name1 = 'Tom'
    name2 = 'Rose'
    
  • 三对引号字符串

    name3 = '''Tom'''
    name4 = """Rose"""
    a = '''
            i am Tom
        '''
    b = '''
            i am Rose
        '''
    c = "I'm Tom"
    d = 'I\'m Tom'
    

字符串输出

name = 'Tom'
print('我的名字是%s' % name)
print(f'我的名字是{name}')

字符串输入

用input()接收用户输入

name = input("输入名字:")
print(f'名字是{name}')
print(type(name))

password = input('输入密码:')
print(f'密码是{password}')
print(type(password))

下标

编号,通过下标快速找到对应的数据。

str1 = 'abcdefg'
print(str1[2])
print(str1[6])

切片

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

语法

序列[开始位置下标:结束位置下标:步长]
  1. 不包含结束位置下标对应的数据,正负整数均可。
  2. 步长是选取间隔,正负整数均可,默认步长为1。

代码

str1 = '012345678'
print(str1[2:5:1])      # 234
print(str1[2:5:2])      #  24
print(str1[2:5])        # 234
print(str1[:5])         # 01234
print(str1[2:])         # 2345678
print(str1[:])          # 012345678

# 负数
print(str1[::-1])       # 876543210
print(str1[-4:-1:])     # 567
print(str1[-4:-1:1])    # 567
# print(str1[-4:-1:-1])
# 选取方向为从左到右,-1步长表示从右向左选
# 如果选取方向和步长方向冲突,则无法选取数据
print(str1[-1:-4:-1])   # 876


字符串常用操作方法

查找

查找子串再字符串中的位置或出现的次数。

语法

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

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

    字符串序列.index(子串,开始位置下标,结束位置下标)
    
  • rfind():和find()功能相同,返回子串最后一次出现的位置。

  • rindex():和index()功能相同,返回子串最后一次出现的位置。

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

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

代码

str = 'hello world and itcast and itkexie and Python'

# 1.find()
print(str.find('and'))      # 12
print(str.find('and',15,30))      # 23
print(str.find('ands'))      # -1

# 2.index()
print(str.index('and'))     # 12
print(str.index('and',15,30))     # 23
# print(str.index('ands'))     # index 查找不存在报错

# 3.count()
print(str.count('and'))     # 3
print(str.count('and',15,30))     # 1
print(str.count('ands'))     # 0

# 4.rfind()
print(str.rfind('and'))     # 35
print(str.rfind('ands'))     # -1

# 5.rindex()
print(str.rindex('and'))    # 35
# print(str.rindex('ands'))

修改

通过函数的形式修改字符串中的数据。

语法

  • replace():替换

    字符串序列.replace(旧子串,新子串,替换次数)
    
  • split():按照指定字符分割字符串。

    字符串序列.split(分割字符,num)
    
  • join():用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串。

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

代码

str = 'hello world and itcast and itkexie and Python'

# 1.replace()
print(str.replace('and','he'))
# hello world he itcast he itkexie he Python
print(str.replace('and','he',10))
# hello world he itcast and itkexie and Python
#替换次数如果超出子串出现的次数,表示替换所有这个子串

# replace 有返回值,返回值是修改后的字符串
# 说明字符串是不可变数据类型
# 数据是否可以改变划分为:可变类型  不可变类型

# 2.split()
print(str.split('and'))
# ['hello world ', ' itcast ', ' itkexie ', ' Python']
print(str.split('and',2))
# ['hello world ', ' itcast ', ' itkexie and Python']

# 3.join()
list = ['aa','bb','cc']
new_str = '...'.join(list)
print(new_str)
# aa...bb...cc

转换大小写

语法

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

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

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

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

代码

str = 'hello world and itcast and itkexie and Python'

# 1.capitalize()
print(str.capitalize())
# Hello world and itcast and itkexie and python

# 2.title()
print(str.title())
# Hello World And Itcast And Itkexie And Python

# 3.lower()
print(str.lower())
# hello world and itcast and itkexie and python

# 4.upper()
print(str.upper())
# HELLO WORLD AND ITCAST AND ITKEXIE AND PYTHON

删除空白字符

语法

  • lstrip():删除字符串左侧空白字符
  • rstrip():删除字符串右侧空白字符
  • strip():删除字符串两侧空白字符

代码

str = '   hello world and itcast and itkexie and Python   '

# 1.lstrip()
print(str.lstrip())
# hello world and itcast and itkexie and Python

# 2.rstrip()
print(str.rstrip())
#    hello world and itcast and itkexie and Python

# 3.strip()
print(str.strip())
# hello world and itcast and itkexie and Python

字符串对齐

语法

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

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

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

代码

str = 'hello'

# 1.ljust()
print(str.ljust(10,'.'))
# hello.....

# 2.rjust()
print(str.rjust(10,'.'))
# .....hello

# 3.center()
print(str.center(11,'.'))
# ...hello...

判断开头结尾

返回的结果是布尔型数据类型:True和False

语法

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

    字符串序列.startwith(子串,开始位置下标,结束位置下表)
    
  • endwith():检查字符串是否以指定子串结尾,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。

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

代码

str = 'hello world and itcast and itkexie and Python'

# 1.startwith()
print(str.startswith('hello'))  # True
print(str.startswith('hel'))    # True
print(str.startswith('hels'))   # False

# 2.endwith()
print(str.endswith('Python'))   # True
print(str.endswith('Pythons'))  # False

判断

语法

  • isalpha():如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False
  • isdigit():如果字符串只包含数字则返回True,否则返回False
  • isalnum():如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False
  • isspace():如果字符串中只包含空白,则返回True,否则返回False

代码

str = 'hello world and itcast and itkexie and Python'

# 1.isalpha():字母
print(str.isalpha())    # False

# 2.isdigit():数字
print(str.isdigit())    # False
str1 = '123456'
print(str1.isdigit())   # True

# 3.isalnum():数字或字母或组合
print(str1.isalnum())   # True
print(str.isalnum())    # False
str2 = 'abc123'
print(str2.isalnum())   # True

# 4.isspace():空白
print(str.isspace())    # False
str3 = '    '
print(str3.isspace())   # True

列表的格式

[数据1,数据2,数据3,数据4……]

列表可以一次性存储多个数据,且可以为不同数据类型。

列表的常用操作

查找

下标

name = ['Tom','Lily','Rose']
print(name[0])  # Tom
print(name[1])  # Lily
print(name[2])  # Rose

函数

语法
  • index():返回指定数据所在位置的下标

    列表序列.index(数据,开始位置下标,结束位置下标)
    
  • count():统计指定数据在当前列表中出现的次数

  • len():访问列表长度,即列表中数据的个数。

代码
name = ['Tom','Lily','Rose']

# 1.index()
print(name.index('Tom'))    # 0
print(name.index('Toms'))   # 报错

# 2.count()
print(name.count('Tom'))    # 1
print(name.count('Toms'))   # 0

# 3.len()
print(len(name))            # 3

判断是否存在

  • in: 判断指定数据在某个列表序列,如果在返回True,否则返回False
  • not in: 判断指定数据不在某个列表序列,如果不在返回True,否则返回False
name = ['Tom','Lily','Rose']

# 1.in
print('Tom' in name)    # True
print('Toms' in name)   # False

# 2.not in
print('Tom' not in name)    # False
print('Toms' not in name)   # True

增加

  • append(): 列表结尾追加数据

    列表序列.append(数据)
    
    name = ['Tom','Lily','Rose']
    
    name.append('xiaoming')
    print(name)
    # ['Tom', 'Lily', 'Rose', 'xiaoming']
    # 列表追加数据的时候,直接在原列表里面追加了指定数据,即修改了原列表,故列表为可变类型数据。
    
    name = ['Tom','Lily','Rose']
    
    name.append([11,22])
    print(name)
    # ['Tom', 'Lily', 'Rose', 'xiaoming', [11, 22]]
    # append()追加的数据是一个序列,则追加整个序列到列表。
    
  • extend(): 列表结尾追加数据,如果数据是一个序列,则将这个序列的数据逐一添加到列表。

    列表序列.extend(数据)
    
    # 单个数据
    name = ['Tom','Lily','Rose']
    
    name.extend('xiaoming')
    print(name)
    # ['Tom', 'Lily', 'Rose', 'x', 'i', 'a', 'o', 'm', 'i', 'n', 'g']
    
    # 序列数据
    name = ['Tom','Lily','Rose']
    
    name.extend(['xiaoming','xiaohong'])
    print(name)
    # ['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaohong']
    
  • insert(): 指定位置新增数据

    列表序列.insert(位置下标,数据)
    
    name = ['Tom','Lily','Rose']
    
    name.insert(1,'xiaoming')
    print(name)
    # ['Tom', 'xiaoming', 'Lily', 'Rose']
    

删除

语法

  • del

    del 目标
    
  • pop(): 删除指定下标的数据(默认最后一个),并返回该数据。

    列表序列.pop(下标)
    
  • remove(): 移除列表中某个数据的第一个匹配项。

    列表序列.remove(数据)
    
  • clear(): 清空列表

代码

name = ['Tom','Lily','Rose']

# 1.del
# del name
# del (name)
# del 可以删除指定下标的数据
del name[0]
print(name)

# 2.pop()
print(name.pop(1))
print(name)

# 3.remove()
name.remove('Rose')
print(name)
# 根据下标判断

# 4.clear()
name.clear()
print(name)

修改

  • 修改指定下标数据

  • 逆置: reverse()

  • 排序: sort()

    列表序列.sort(key = None, reverse = False)
    # reverse = True 降序,reverse = False 升序(默认)
    
sorted排序效果同sort,不改变原列表的顺序,sort改变原列表顺序。
元组只能用sorted,不能用sort

代码

name = ['Tom','Lily','Rose']

# 1.修改指定下标
name[0] = 'aaa'
print(name)
# ['aaa', 'Lily', 'Rose']

# 2.逆序 reverse()
list = [1,3,2,8,4,6,9]
list.reverse()
print(list)
# [9, 6, 4, 8, 2, 3, 1]

# 3.sort()
list.sort()
# [1, 2, 3, 4, 6, 8, 9]
list.sort(reverse=False)
# [1, 2, 3, 4, 6, 8, 9]
list.sort(reverse=True)
# [9, 8, 6, 4, 3, 2, 1]
sorted(list)
print(list)

复制

copy()

name = ['Tom','Lily','Rose']
list = name.copy()
print(list)
# ['Tom', 'Lily', 'Rose']

列表的循环遍历

while

name = ['Tom','Lily','Rose']

i = 0
while i < len(name):
    print(name[i])
    i += 1

for

name = ['Tom','Lily','Rose']

for i in name:
    print(i)

列表嵌套

name = [['小明','小红','小绿'],['Tom','Lily','Rose'],['张三','李四','王五']]

print(name)
print(name[0])  # ['小明', '小红', '小绿']
print(name[1][1])   # Lily

随机分配办公室

8个老师随机分配到3个办公室

import random

# 数据
teachers = ['A','B','C','D','E','F','G','H']
offices = [[],[],[]]

# 分配老师到办公室
for name in teachers:
    # 随机办公室
    num = random.randint(0,2)
    # 老师追加到办公室列表
    offices[num].append(name)

i = 1
# 验证是否分配成功
for office in offices:
    print(f'办公室{i}的人数是{len(office)},老师是: ')
    for name in office:
        print(name)

    i += 1

一个元组可以存储多个数据,元组内的数据是不能修改的。

定义元组

特点:定义元组使用小括号,且逗号隔开各个数据,数据可以是不同的数据类型。

# 多个数据元组
t1 = (10,20,30)

# 单个数据元组
t2 = (10,)
t1= (10,)
print(type(t1))   # typle

t2 = (20)
print(type(t2))   # int

t3 = ('aaa')
print(type(t3))   # str

t4 = ('aaa',)
print(type(t4))   # tuple

常见操作

方法

元组数据不支持修改,只支持查找。

  • 按下标查找数据
  • index() : 查找某个数据,如果数据存在返回对应的下标,否则报错,语法和列表、字符串的index方法相同。
  • count() : 统计某个数据在当前元组出现的次数。
  • len() : 统计元组中数据的个数。

代码

t1 = ('aa','bb','cc','dd')

# 1.下标
print(t1[0])            # aa

# 2.index()
print(t1.index('bb'))   # 1
print(t1.index('bbb'))  # 报错

# 3.count()
print(t1.count('aa'))   # 1
print(t1.count('aaa'))  # 0

# 4.len()
print(len(t1))          # 4

修改

如果元组里面有列表,修改列表里面的数据是支持的。

t2 = ('aa','bb',['cc','dd'])
print(t2[2][0])
t2[2][0] = 'edgnb'
print(t2)

字典里面的数据以键值对形式出现,字典数据和数据顺序没有关系,字典不支持下标。

创建字典

字典特点:

  • 符号为大括号
  • 数据为键值对形式出现
  • 各个键值对之间用逗号隔开
# 1.有数据的字典
dict1 = {'name':'Tom','age':20,'gander':'男'}
print(dict1)

# 2.空字典
dict2 = {}
print(dict2)

dict3 = dict()

字典常见操作

字典序列[key] =
dict1 = {'name':'Tom','age':20,'gander':'男'}

dict1['id'] = 111
print(dict1)

dict1['name'] = 'Rose'
print(dict1)

删除

  • del() / del : 删除字典或删除字典中指定键值对。
  • clear() : 清空字典
dict1 = {'name':'Tom','age':20,'gander':'男'}

# 1.del
del dict1
print(dict1)
del dict1['name']
del dict1['names']    # 报错
print(dict1)

# clear()
dict1.clear()
print(dict1)

修改

写法和增加一样,存在就是修改。

  • key值查找

  • get()

    字典序列.get(key,默认值)
    # 如果当前查找的key不存在则返回第二个参数(默认值),如果省略第二个参数,则返回None
    
  • keys() : 查找字典中所有的key,返回可迭代对象(可以用for遍历)

  • values() : 查找字典中所有的value,返回可迭代对象

  • items() : 查找字典中所有的键值对,返回可迭代对象,里面的数据是元组,元组数据1是字典的key,元组数据2是字典key对应的值。

示例

dict1 = {'name':'Tom','age':20,'gander':'男'}

# 1.key
print(dict1['name'])    # Tom
print(dict1['names'])   # 报错

# 2.函数
# 2.1 get()
print(dict1.get('name'))    # Tom
print(dict1.get('names'))   # None
print(dict1.get('names','Lily'))    # Lily

# 2.2 keys()
print(dict1.keys()) # dict_keys(['name', 'age', 'gander'])

# 2.3 values()
print(dict1.values())   # dict_values(['Tom', 20, '男'])

# 2.4 items()
print(dict1.items())    # dict_items([('name', 'Tom'), ('age', 20), ('gander', '男')])

# 查指定key的value
print(dict1.['name'])	# Tom

循环遍历

遍历字典的key

dict1 = {'name':'Tom','age':20,'gander':'男'}

for key in dict1.keys():
    print(key)
    
# name
# age
# gander

遍历字典的value

dict1 = {'name':'Tom','age':20,'gander':'男'}

for value in dict1.values():
    print(value)
    
# Tom
# 20
# 男

遍历字典的元素

dict1 = {'name':'Tom','age':20,'gander':'男'}

for item in dict1.items():
    print(item)
    
# ('name', 'Tom')
# ('age', 20)
# ('gander', '男')

遍历字典的键值对

拆包

dict1 = {'name':'Tom','age':20,'gander':'男'}

for key,value in dict1.items():
    print(f'{key} = {value}')
    
# name = Tom
# age = 20
# gander = 男

创建集合

创建集合使用{}或set{},但是如果要创建空集合只能使用set{},{}用来创建空字典。

s1 = {10,20,30,40,50}
print(s1)

s2 = {10,20,30,40,50,20,30,10}
print(s2)
# 集合去重

s3 = set('abcdefg')
print(s3)

s4 = set()
print(s4)
print(type(s4))     # set

s5 = {}
print(type(s5))     # dict

set() 创建可变集合
frozenset() 创建不可变集合

集合常见操作

增加数据

  • add() :

  • update() : 追加的数据是序列

示例

s1 = {10,20}

# 1.集合是可变类型
# add()
s1.add(100)
print(s1)

s1.add(100)     # 重复
print(s1)

s1.add([10,20,30])
print(s1)       # 用来追加单一数据,追加序列报错

# update()
s1.update([10,20,30,40,50])
print(s1)

s1.update(100)  # 报错
print(s1)       

删除数据

  • remove() : 删除集合中的指定数据,如果数据不存在则报错。
  • discard() : 删除集合中的指定数据,如果数据不存在也不会报错。
  • pop() : 随机删除集合中的某个数据,并返回这个数据。

示例

s1 = {10,20,30,40,50}

# remove()
s1.remove(10)
print(s1)

s1.remove(10)   # 报错
print(s1)

# discard()
s1.discard(10)
print(s1)

# pop()
num = s1.pop()
print(num)
print(s1)

查找数据

  • in : 判断数据在集合序列
  • not in : 判断数据不在集合序列

示例

s1 = {10,20,30,40,50}

# in
print(10 in s1)     # True
print(10 not in s1) # False
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值