Day04 - 字符串元组列表字典

Python 官方中文文档
https://docs.python.org/zh-cn/3/

0. 字符串常用方法

a.查找_替换_统计
	find()  掌握		注意: 找不到子串时,返回-1
	rfind() 了解
	index() 了解		注意: 找不到子串时,程序会崩溃,产生一条异常信息,导致程序无法执行
	rindex() 了解 
	replace() 掌握   默认全部替换
	count()	掌握     
'''
a.查找_替换_统计
find()  掌握
rfind() 了解
index() 了解
rindex() 了解
replace() 掌握
count()	掌握
'''

s = 'Hello World Hello World Hello Python'


# find()
def test_find():
    # find 查找
    idx = s.find('orld')
    print(idx)

    idx = s.find('orld', 8, 20)
    print(idx)


# test_find()

# index()
def test_index():
    idx = s.index('orld')
    print(idx)

    idx = s.index('orld', 8, 20)  # ValueError: substring not found

    print(idx)


# test_index()


# rfind() rindex()
def test_rfind_rindex():
    print(s.rfind('o'))
    print(s.rindex('o'))

    print(s.rfind('kk'))
    print(s.rindex('kk'))


print(len(s))


# test_rfind_rindex()


# replace() 替换
def test_replace():
    # 替换 时默认替换 所有的符合的子串
    print(s.replace('l', 'L'))
    print(s)

    # 最后听参数三表示替换个数
    print(s.replace('l', 'L', 3))


test_replace()


# count 计数统计

def test_count():
    print(s.count('o'))
    print(s.count('o', 1, 5))


test_count()

print(f'a{0:5}b')

b. 分割_连接
	split()	掌握  输出的是列表,需要注意有分隔符,且每个都会生效
	splitlines() 理解  注意只识别换行为分隔符

	partition()	 了解  只会分割成三部分,且输出一个元组
	rpartition() 了解
	join() 掌握  加入字符进行连接列表中的每个元素
'''
 分割_连接
split()	掌握  输出的是列表,需要注意有分隔符,且每个都会生效
splitlines() 理解  注意只识别换行为分隔符

partition()	 了解  只会分割成三部分,且输出一个元组
rpartition() 了解
join() 掌握  加入字符进行连接列表中的每个元素
'''

s = 'Hello World Hello World Hello Python'


# split() 分割
def test_split():
    ret = s.split(' ')
    print(ret)
    print(type(ret))

    ret = s.split('o')
    print(ret)

    ret = s.split('ll')
    print(ret)

    # 参数一是 要分割的条件字符串,
    # 参数二是 最大分割次数
    ret = s.split('ll', 1)
    print(ret)

    ss = 'Hello\tWorld Hello \t\nWorld Hello\n Python'
    print(ss)
    # 如果在分割字符串时,需要使用任何空白进行分割,那么参数中,什么也不需要写
    print(ss.split())


# test_split()


# splitlines() 按行分割
def test_splitlines():
    ss = 'Hello\tWorld Hello \t\nWorld Hello\n Python'
    print(ss.splitlines())

    print(ss.split('\n'))


# test_splitlines()


# partition 分割
# 按分割条件将字符串分割成三部分,分割条件前,分割条件,分割条件后

def test_partition():
    ss = 'HellohahaHelloHellohahaHello'
    print(ss.partition('haha'))

    # rpartition() 从右侧进行分割
    ss = 'HellohahaHelloHellohahaHello'
    print(ss.rpartition('haha'))


# test_partition()


# join() 使用当前字符串连接参数中的每个元素

def test_join():
    ss = 'Hello World Python'
    print('-'.join(ss))

    # join 的作用
    s_ss = ss.split()
    print(s_ss)
    # j_ss = '$'.join(s_ss)
    j_ss = '_'.join(s_ss)
    print(j_ss)

    print('$'.join('AB'))


test_join()

c. 判断
	startswith() 判断是否以指定字符串开头 (掌握)
	endswith()   判断是否以指定字符串结束 (掌握)
	isupper()	判断是不是大写字符	(理解)
	islower()	判断是不是小写字符	(理解)
	isdigit()	判断是不是数字字符 (理解)
	isalpha()	判断是不是字母 (理解)
	isalnum()	判断是不是字母或数字字符 (理解)
	isspace()	判断是不是空白字符,包含空格,换行符\n,制表符\t (理解)注意''空字符串不是空白字符
'''
startswith() 判断是否以指定字符串开头 (掌握)
endswith()   判断是否以指定字符串结束 (掌握)
isupper()	判断是不是大写字符	(理解)
islower()	判断是不是小写字符	(理解)
isdigit()	判断是不是数字字符 (理解)
isalpha()	判断是不是字母 (理解)
isalnum()	判断是不是字母或数字字符 (理解)
isspace()	判断是不是空白字符,包含空格,换行符\n,制表符\t (理解)注意''空字符串不是空白字符
'''


# startswith() 判断是否以指定字符串开头 (掌握)
def test_startswith():
    print('13800138000'.startswith('138'))
    print('18300138000'.startswith('138'))
    print('18700138000'.startswith('138'))
    print('13300138000'.startswith('138'))


# test_startswith()

# endswith()   判断是否以指定字符串结束 (掌握)

def test_endswith():
    print('www.xxxgov.com'.endswith('.gov'))
    print('www.xxx.gov'.endswith('.gov'))


# test_endswith()


def test_other():
    # print('hello'.isupper())
    # print('Hello'.isupper())
    # print('HELLO'.isupper())

    # print('hello'.islower())
    # print('Hello'.islower())
    # print('HELLO'.islower())

    # print('hello'.isalpha())
    # print('Hello'.isalpha())
    # print('HELLO'.isalpha())
    # print('123'.isalpha())
    # print('abc123'.isalpha())

    # print('HELLO'.isalnum())
    # print('123'.isalnum())
    # print('abc123'.isalnum())
    # print('abc 123'.isalnum())

    # print('HELLO'.isdigit())
    # print('123'.isdigit())
    # print('abc123'.isdigit())
    # print('123abc'.isdigit())

    print(''.isspace())
    print(' '.isspace())
    print('\t'.isspace())
    print('\n'.isspace())


test_other()
d. 转换 (理解)
	upper() 转换成大写
	lower() 转换成小写
	title() 将每个单词首字符转换大写
	capitalize() 将第一个单词的首字符转换成大写
'''
转换 (理解)
upper() 转换成大写
lower() 转换成小写
title() 将每个单词首字符转换大写
capitalize() 将第一个单词的首字符转换成大写
'''

s = 'Hello world Python JAVA asdfhaslkjf'

print(s.upper())

print(s.lower())

print(s.title())

print(s.capitalize())

e. 对齐 (理解)
	center()	按给定宽度居中显示
	rjust()		右对齐
	ljust()		左对齐
'''
 对齐 (理解)
		center()	按给定宽度居中显示
		rjust()		右对齐
		ljust()		左对齐
'''
s = 'Hello'
print(s)
print('|' + s.center(11) + '|')
print('|' + s.center(11, '_') + '|')

# r -> right
print('|' + s.rjust(11) + '|')
print('|' + s.rjust(11, '_') + '|')

# l -> left
print('|' + s.ljust(11) + '|')
print('|' + s.ljust(11, '_') + '|')

f. 去除空白(理解)
	strip()		去除两端空白
	lstrip()	去除左侧空白
	rstrip()	去除右侧空白
'''
去除空白(理解)
		strip()		去除两端空白
		lstrip()	去除左侧空白
		rstrip()	去除右侧空白
'''

s = '    hello     world      '
print(s)

print('|' + s.strip() + '|')
print('|' + s.rstrip() + '|')
print('|' + s.lstrip() + '|')

ret = s.split()
ret = ''.join(ret)
print(ret.center(20))

print(5.0 // 3)

1. 元组

a. 定义和下标访问
元组的格式: (值,....)
元组的类型: tuple
元组的下标使用同字符串

注意:如果元组中只有一个元素,那么在定义时,需要加一个逗号

b. 遍历
	# for-in
	t = (1,2,3,4,5,'hello')
	for v in t:
		print(v)
'''
元组的定义和下标使用
'''

# 元组的定义

# 定义一个空元组
t1 = ()
print(t1)
print(type(t1))

# 定义包含元素的元组
t2 = (1, 2, 3, 4, 5)
print(t2)
print(type(t2))

# 定义包含其它数据类型的元组
t3 = ('a', 'b', 'hello', 'world')
print(t3)

# 元组的复杂定义形式
t4 = (1, 3.14, 'Hello', True, t3)
print(t4)

# 定义具有一个元素的元组,特殊,注意,重点
t5 = (1,)
print(t5)
print(type(t5))

# 使用类型名定义元组
t6 = tuple()
print(t6)

t7 = tuple('hello')
print(t7)

# 元组的下标访问
t8 = (1, 2, 3, 4, 5, 6, 7, 8)
print(t8[0])
print(t8[3])
print(t8[7])
# 元组也不能使用超出范围的下标,会出现越界错误
# print(t8[70])  # IndexError: tuple index out of range

# 元组是一种 不可变类型,不能修改元组中的元素值 ,修改会报错
# t8[0] = 1111  #TypeError: 'tuple' object does not support item assignment

	# 循环配合下标方式 一
	for i in range(len(t)):
		print(t[i])
'''
元组的遍历
'''

last_name = ('张','王')
first_name = ('博','三','四')


# for-in
t = (1,2,3,4,5,'hello')
for v in t:
    print(v)


# 循环配合下标方式 一
for i in range(len(t)):
    print(t[i])


# 循环配合下标方式 二
i = 0
while i < len(t):
    print(t[i])
    i += 1


	# 循环配合下标方式 二
	i = 0
	while i < len(t):
		print(t[i])
		i += 1
c. 嵌套元组
'''
元组的嵌套及遍历
'''

# 定义一个嵌套元组
t = (1, 2, 3, (4, 5, 6), (7, 8, 9))

# 遍历
for v in t:
    # isinstance() 判断参数一是否是参数二的类型对象
    # 通过 isinstance 判断 遍历的元素是否是一个元组,
    # 如果是就继续遍历,不是直接 输出
    if isinstance(v, tuple):
        for v2 in v:
            print(v2)
    else:
        print(v)

d. 常用方法
	功能同字符串
	count() 用来统计元素个数
	index() 查找元素的位置索引,如果不存在会报错
'''
元组的常用 方法
'''

t = (1, 2, 3, 4, 55, 5, 5, 6, 6, 2, 3, 2)

# 提示中方法名前面的 m 表示 是一个方法, method
print(t.count(2))
print(t.index(2))
print(t.index(2, 3, 5))  # ValueError: tuple.index(x): x not in tuple

3. 列表

a. 定义和下标访问
	定义格式:
	变量名 = [值,....] 
	变量名 = list(值)

	下标:
	0~len(列表名)-1
'''
列表的定义和下标访问
'''

# 定义一个空列表
cl1 = []
print(cl1)
print(type(cl1))

# 定义一个具有一个元素的列表
cl2 = [1, ]
print(cl2)
print(type(cl2))

# 定义具有多个元素的列表
cl3 = [1, 2, 3, 'hello', (4, 5, 6), ['a', 'b', 'c']]
print(cl3)
print(type(cl3))

for v in cl3:
    if isinstance(v, tuple) or isinstance(v, list):
        for i in v:
            print(i)
    else:
        print(v)

# 使用list()创建 列表 对象
# cl4 = list()  # 空列表
cl4 = list('hahaha')
print(cl4)
print(type(cl4))

# 通过下标访问列表中的元素
cl5 = [1, 2, 3, 4, 5]
print(cl5[0])
print(cl5[3])
print(cl5[4])
# print(cl5[10]) #IndexError: list index out of range


# 重点:列表 的特性,可以通过 下标修改对应位置上的数据
print(cl5)
cl5[0] = 999
print(cl5)

# 字符串逆序
s = 'hello'


def revers_str(s):
    # 定义一个空字符串,用来拼接
    ret_s = ''
    i = len(s) - 1
    while i >= 0:
        ret_s += s[i]
        i -= 1

    return ret_s


print(revers_str(s))
b. 遍历
	同字符串或元组


c. 嵌套列表定义和遍历
	isinstance(obj,type) -> bool

d. 排序和逆序
	sort(reverse=False)
	reverse()
'''
列表 的排序和逆序
'''

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

print(cl)
# 排序 默认升序排序(从小到大)
print(cl.sort())
print(cl)

cl = [9, 2, 5, 7, 1, 8, 4, 3, 0, 6]
# 降序排序 (从大到小)
cl.sort(reverse=True)
print(cl)

# 逆序
cl = [9, 2, 5, 7, 1, 8, 4, 3, 0, 6]

# 逆序是直接将原列表中的顺序进行逆转
cl.reverse()
print(cl)


# 实现列表逆序方法
def reverse_list(cl):
    # 定义一个空列表
    ret_l = []
    i = len(cl) - 1
    while i >= 0:
        ret_l.append(cl[i])  # s += c
        i -= 1

    return ret_l


print(reverse_list(cl))

'''
l = [1,2,3,4,5]
l[0]
l[4]
l = [5,2,3,4,1]
l[1]
l[3]
l = [5,4,3,2,1]





'''
e. 常用方法
	增:
		append()
		extend()
		insert()
'''
增:
			append()
			extend()
			insert()
'''

# append 追加数据
cl = []
cl.append(1)
cl.append(2)
cl.append(3)
cl.append('hello')
print(cl)
cl.append(['a', 'b'])
print(cl)

# extend() 扩展
# 可以将参数中的容器对象中的每个元素添加扩展到源列表中
cl1 = [1, 2, 3]
cl2 = ['a', 'b', 'c', [5, 6]]
# cl1.append(cl2)
cl1.extend(cl2)
print(cl1)

# insert 插入
cl3 = [1, 2, 3, 4, 5]
cl3.insert(0, 999)
print(cl3)
cl3.insert(2, 888)
print(cl3)
cl3.insert(7, 777)
print(cl3)

# 注意:在插入数据时,没有下标越界问题
# 如果指定下标超过元素正常范围,相当于追加
cl3.insert(17, 666)
print(cl3)
	修:
		下标修改

	查:
		index()
		count()
		in (掌握)
		not in
'''
列表 操作-查找
'''

l = [1, 2, 3, 4, 5, 6, 6, 6, 6, 6, 2, 3]

# count()
print(l.count(6))
print(l.count(66))

# index()
print(l.index(6))
print(l.index(2))
# print(l.index(22))  # ValueError: 22 is not in list

# in - not in
print(2 in l)
print(22 in l)

print(2 not in l)
print(22 not in l)

	删:
		pop()
		remove()
		clear() 清空但列表存在
		del 全没了
'''
删:
			pop()
			remove()
			clear() 清空但列表存在
			del 全没了
'''

cl = [1, 2, 3, 4, 5, 6, 7, 3, 7, 8, 90, 91, 0]

# pop()
# pop 中的 index 参数可以不写,默认删除 最后一个
cl.pop()
print(cl)

cl.pop(0)
print(cl)

# remove
# 删除 指定对象,当有多个相同对象时,只删除 第一个
cl.remove(7)
print(cl)

# del 有两种 方式

del cl[1]
print(cl)

del (cl[1])
print(cl)

# 将整个列表删除
# del cl
# del(cl)

print(cl)  # NameError: name 'cl' is not defined

# clear()
# 清空列表元素

cl.clear()
print(cl)

# 在使用列表时,不要在循环遍历时删除元素

cl = [5, 3, 8, 91]

for o in cl:
    cl.remove(o)

print(cl)

4. 字典概述,定义

字典定义格式
{key: value,....}
'''
定义字典
'''

d = {}  # dictionary -> dict
print(d)
print(type(d))

# 理论,所以不可变的类型都可以做为key,
# 只要是可hash的的对象都 可以做为key
# key一般情况下使用字符串类型的数据充当,
d = {1: 'one', '2': 'two'}
print(d)

d = {'one': '星期一', 'two': '星期二', 'three': '星期三'}
print(d)

5. 字典的元素的引用

'''
访问字典中的元素
'''

d = {'one': '星期一', 'two': '星期二', 'three': '星期三','haha':'周末'}
print(d)

# 字典也是通过下标方式 来访问元素,但是字典中没有索引,也就是没有下标编号
# 字典通过下标的中括号中书写key的方式 来直接 访问key所对应的值
print(d['one'])
print(d['two'])
print(d['haha'])
# print(d['hahaha']) # KeyError: 'hahaha' 访问时,如果使用了不存在的key,会报错

# 字典也是一个可变类型
d['haha'] = '星期日'
print(d)

在这里插入图片描述

使用字典获取字典中的数据
格式:
字典变量名[key]
字典变量名.get(key)
'''
字典中的数据访问
'''
d = {'one': '星期一', 'two': '星期二', 'three': '星期三', 'haha': '周末'}

print(d['one'])
print(d.get('one'))

# print(d['onee'])
#  下标方式 在访问数据时,如果key不存在,会报错
# get方法方式 访问数据时,如果key不存在,返回None
print(d.get('onee'))

6. 遍历字典

四种遍历方式-看代码
'''
字典元素的遍历
'''
# 方式 一

d = {'one': '星期一', 'two': '星期二', 'three': '星期三', 'haha': '周末'}

# 默认情况 下,使用for-in遍历时,会将所有的key遍历出来
for k in d:
    print(f'for-in:{k} --> {d[k]}')

# 方式二
# keys()方法
print(d.keys())
for k in d.keys():
    print(f'keys  :{k} --> {d[k]}')

# 方式三
# values() 方法
print(d.values())
for v in d.values():
    print(f'values: {v}')

# 方式 四
# items()
print(d.items())

for item in d.items():
    print(f'items: {item[0]}--》{item[1]}')

for k, v in d.items():
    print(f'item: {k}--> {v}')

# 解包
item = (1, 2, 3, 4, 5, 6)
a, b, c, d, e = item

print(a)
print(e)

7. 字典增删改查

'''
字典的增删改查
'''

d = {}

# 增
# 如果在赋值时,使用的key在字典中不存在,那么就是向字典中添加 数据
d['a'] = 1
d['b'] = 2
d['c'] = 2
d['d'] = 2
d['e'] = 5
print(d)

# 改
# 如果在赋值 时,使用的key在字典中存在,那么就修改这个key所对应的值
# 注意:
# 字典中的key 具有唯一性
# 如果key不存在,那么就是添加 数据,如果key存在就是修改数据
# key 是不能修改的

d['a'] = 11
print(d)

# 查
print(d['a'])
print(d.get('a'))

# 删除
# popitem 删除 最后一个键值对
# d.popitem()
# print(d)
# d.popitem()
# print(d)

# pop(key)
# pop 可以通过 指定 key来删除 任意位置的键值对
print(d)
d.pop('c')
print(d)

# 清空字典中的键值对
# d.clear()
# print(d)

# del
del d['e']
print(d)

del d
print(d)

在这里插入图片描述

8. 字典练习(名片管理)

函数一: 建立名片-> 建立好的名片
函数二: 显示名片-> 接收谁打印谁
'''
字典练习(名片管理)
	函数一: 建立名片-> 建立好的名片
	函数二: 显示名片-> 接收谁打印谁
'''


# 定义字典的函数

def creat_card():
    # 使用字典来保存每张名片的数据
    # name,age,address
    card = {}
    card['name'] = input('请输入姓名:')
    card['age'] = input('请输入年龄:')
    card['address'] = input('请输入地址:')

    return card


# 显示 名片字典内容函数
def show_card(card):
    for k in card:
        print(f'{k} : {card.get(k)}')


# 测试
show_card(creat_card())

9. 无序字典和有序字典

在 python3.5之前, dict 类型是无序的 ,key无序,-> 写入顺序和显示顺序不同
在 pyhton3.5之后,都是有序
'''
有序字典
'''

d = {'a': 1, 'd': 4, 'b': 2, 'c': 3}
print(d)

from collections import OrderedDict

# 3.5版本以后的有序是指  定义顺序和显示顺序一致

10. 集合定义和引用

集合的特性:
	集合定义像字典
	存储数据像列表

	重要特性:
	集合中的数据不允许重复


作用:
	利用集合的特性来对数据进行去除重复数据

定义:
	set(可遍历的对象)


访问:
'''
集合的使用
'''

# 定义一个集合

s = {1, 2, 3, 4, 5, 6, 7, 7, 7}
print(s)

# 定义一个空集合
# s = {} # 这种方式 是定义一个空字典,不是集合
s = set()
print(s)
print(type(s))

s = {1, 2, 3, 4, 5, 6, 7, 7, 7}

for v in s:
    print(v)

# 注意: 集合是不支持下标的
print(s[0])

11. set-list-tuple三者类型间转换

'''
set-list-tuple三者类型间转换
'''

s = 'hello'

l = list(s)
print(l)

print(set(l))

print(set(s))

l1 = str(l)  # __str__
print(l1, '-----', type(l1))
print(''.join(l))

12. 公共方法和内置函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

李好秀

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

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

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

打赏作者

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

抵扣说明:

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

余额充值