首页 > 其他分享 >Day04 - 字符串元组列表字典

Day04 - 字符串元组列表字典

时间:2023-01-23 17:23:41浏览次数:57  
标签:cl Day04 test key print 元组 字典

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. 公共方法和内置函数

标签:cl,Day04,test,key,print,元组,字典
From: https://www.cnblogs.com/lehoso/p/17065311.html

相关文章

  • Day04-if分支+循环语句
    一、if判断语句1、语句结构if条件语句:    满足条件运行的代码1    满足条件运行的代码22、if嵌套结构if条件语句1:  满足条件运行的代码1满足条件运......
  • Python语言基础—元组的应用与常见操作
    希望本阶段内容可以帮助大家学好Python基础,详情可以关注上方Python专栏!文章目录​​系列文章目录​​​​一、元组的应用场景​​​​二、定义元组​​​​三、元组的常见操......
  • trie 字典树
    简介trie树(字典树),又称单词查找树,是一种树形结构,哈希树的变种。trie以字符为索引建树,因此,查找时间不带\(log\),而是由字符串长度决定。满trie树(原创图)。但这张图不足......
  • golang字典生成算法实现(全排列实现)
    packagemain//@Title main.go//@Description 入口文件//@Author xiao//@Update noneimport( "flag" "fmt" "log")//字典常量const( lowerCaseChar......
  • Day04-运算符
    一、算术运算符以下假设变量:a=10 b=20运算符描述实例+加 - 两个对象相加a + b 输出结果 30-减 - 得到负数或是一个数减去另一个......
  • C#元组和类的静态方法/类方法的有效范围
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacelearn_hide_function{intern......
  • python 字典
    通俗理解字典就是Java中的map定义字典遵循k:string,v:obj的模式,也就是说,除了基本数据类型,v可以是对象,列表等等。dictionary={'name':'jack',age:19}操作字典新增属......
  • Python导入Excel表格数据并以字典dict格式保存
      本文介绍基于Python语言,将一个Excel表格文件中的数据导入到Python中,并将其通过字典格式来存储的方法。  我们以如下所示的一个表格(.xlsx格式)作为简单的示例。其中,表......
  • 字典字段包含逗号,使用GROUP_CONCAT 及 FIND_IN_SET 查出目标数据
    说明:查出(11,22,44)对应(李三,王五,高胖) 的效果 GROUP_CONCAT连接函数FIND_IN_SET(需要查询的id,(11,22,33,44))       selectGROUP_CONCAT(psyt.item_text),rp.id......
  • day04-Spring管理Bean-IOC-02
    Spring管理Bean-IOC-022.基于XML配置bean2.7通过util空间名称创建listBookStore.java:packagecom.li.bean;importjava.util.List;/***@author李*@version......