【笔记】2022.4.21~22 元组、集合、字符串笔记

1. 元组


1.1 什么是元组(tuple)


1.1.1 元组的三要素

(1)元组是一种容器型数据类型:将()作为容器的标志,里面多个元素用逗号隔开:(元素1, 元素2, 元素3, …)

(2)元组是不可变的;有序的(支持下标操作)

(3)元组对元素的要求:任何数据


1.1.2 元组的注意点

(1)空元组

RIGHT Example:

t1 = ()

(2)只有一个元素的元组(重点)

WRONG Example:

t2 = (100,)
print(t2, type(t2))
# 100 <class 'int'>

RIGHT Example:

t2 = (100,)
print(t2, type(t2), len(t2))
# (100,) <class 'tuple'>

(3)在没有歧义的情况下,元组的小括号可以省略:直接将多个数据用逗号隔开,表示的也是一个元组

RIGHT Example:

# 情况1:没歧义
t3 = (10, 20, 30)
print(t3)  # (10, 20, 30)

t3 = 10, 20, 30
print(t3)  # (10, 20, 30)

# 情况2:有歧义
t3 = 10, 20, 30 * 3
print(t3)  # (10, 20, 90)

t3 = (10, 20, 30) * 3
print(t3)  # (10, 20, 30, 10, 20, 30, 10, 20, 30)

1.2 元组就是不可变的列表

列表中除了和可变相关的操作,其他操作元组都支持

【笔记】2022.4.18~19 列表

注意:支持sorted,不支持sort


2. 集合


2.1 什么是集合(set)


2.1.1 集合的三要素

(1)集合是一种容器型数据类型:将{}作为容器的标志,里面多个元素用逗号隔开:{元素1, 元素2, 元素3, …}

(2)集合是可变的;无序的(不支持下标操作)

(3)集合对元素的要求:和字典对键的要求一样(不可变的数据;唯一的)


2.1.2 集合的注意点

(1)空集合

WRONG Example:

s1 = {}
print(type(s1), len(s1))
# <class 'dict'> 0

RIGHT Example:

s1 = set()
print(type(s1), len(s1))
# <class 'set'> 0

(2)集合无序

RIGHT Example:

print({1, 2, 3} == {3, 2, 1})  
# True

(3)元素是不可变类型的数据

RIGHT Example:

s2 = {10, 'abc', (1, 2)}
print(s2)

s3 = {10, 'abc', [1, 2]}  # 报错

(4)元素是唯一的:可以用来去重

注意:元素必须是不可变元素才能转成集合

RIGHT Example:

s3 = {10, 20, 10, 10, 30, 20}
print(s3)
# {10, 20, 30}

2.2 数学集合运算

包括:&(交集)、|(并集)、-(差集)、^(对称差集)、>、<、>=、<=

布鲁斯韦恩图:
在这里插入图片描述
(1)集合1 & 集合2:获取两个集合的公共部分

RIGHT Example:

s1 = {1, 2, 3, 4, 5, 6, 7}
s2 = {5, 6, 7, 8, 9, 10}
print(s1 & s2)
# {5, 6, 7}

(2)集合1 | 集合2:合并两个集合

RIGHT Example:

print(s1 | s2)
# {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

(3)集合1 - 集合2:

RIGHT Example:

print(s1 - s2)
# {1, 2, 3, 4}

print(s2 - s1)
# {8, 9, 10}

(4)集合1 ^ 集合2

RIGHT Example:

print(s1 ^ s2)
# {1, 2, 3, 4, 8, 9, 10}

(5)>、<:判断是否是真子集

RIGHT Example:

print(s1 ^ s2)
# {1, 2, 3, 4, 8, 9, 10}

(6)>=、<=:判断是否是子集

RIGHT Example:

print(s1 ^ s2)
# {1, 2, 3, 4, 8, 9, 10}

附:子集和真子集
{1, 2, 3}
子集:{}、{1}、{2}、{3}、{1, 2}、{1, 3}、{2, 3}、{1, 2, 3}
真子集:{}、{1}、{2}、{3}、{1, 2}、{1, 3}、{2, 3}


3. 字符串


3.1 什么是字符串


3.1.1 字符串的三要素

(1)字符串是容器型数据类型:将’‘、“”、’‘’‘’'、“”“”""作为容器的标志,引号中的每个符号就是字符串的元素

(2)字符串是不可变的;字符串有序(支持下标操作)

RIGHT Example:

str1 = 'abc23红色经典mn*.....❤'
new_str = str1.upper()

print(str1)
# abc23红色经典mn*.....❤

print(new_str)
# ABC23红色经典MN*.....❤

(3)元素:引号中的每个元素就是字符串的元素,字符串的元素又叫字符


3.1.2 字符串的注意点

(1)引号中的每个元素就是字符串的元素,对于符号本身没有限制

RIGHT Example:

str = '❤❥웃유♋☮✌☏☢☠✔☑♚▲♪✈✞÷↑↓◆◇⊙■□△▽¿─│♥❣♂♀☿Ⓐ✍✉☣☤✘☒♛▼♫⌘☪≈←→◈◎☉★☆⊿※'

(2)引号问题

RIGHT Example:

str2 = 'abc'
str3 = "abc"
str4 = '''abc'''
str5 = """abc"""
print(type(str2), type(str3), type(str4), type(str5))
<class 'str'> <class 'str'> <class 'str'> <class 'str'>

(3)多行字符串:三个引号开头的字符串,字符串内容可以直接按回车换行

RIGHT Example:

str1 = '''abc
123'''
print(str1)

str1 = 'abc\n123'
print(str1)

(4)空串

RIGHT Example:

str1 = ''
str2 = ' '

print(len(str1), type(str1))
# 0 <class 'str'>

print(len(str2), type(str2))
# 1 <class 'str'>

3.2 字符

字符串的元素


3.2.1 普通字符:在字符串中表示符号本身的字符就是普通字符

RIGHT Example:

print('a8*开始')
# a8*开始

3.2.2 转义字符

在特定的符号前加\来表示特殊功能或者特殊意义的符号就是转义字符

(1)\t:水平制表符(相当于按一个tab键)

RIGHT Example:

print('abc')
# abc

print('\tabc')
# 	abc

(2)\n:换行

RIGHT Example:

print('123abc')
# 123abc

print('123\nabc')
"""
123
abc
"""

(3)\ ':表示一个普通的单引号

WRONG Example:

print('it's me')
# 报错,SyntaxError: invalid syntax

RIGHT Example:

print('it\'s me')
print("it's me")

# it's me

(4)\ ":表示一个普通的双引号

WRONG Example:

print("I say:"you see see, one day day"")
# 报错,SyntaxError: invalid syntax

RIGHT Example:

print("I say:\"you see see, one day day\"")
print('I say:"you see see, one day day"')

# I say:"you see see, one day day"

(5)\ \:表示一个普通的反斜杠

RIGHT Example:

print('\\tabc\n123')
"""
\tabc
123
"""

(6)R语法:字符串的最前面可以加r或者R,让字符串中所有的转义字符功能消失,所有的符号都变成普通字符:r’‘、R’’

RIGHT Example:

str1 = '\tabc\n123\u4e00'
print(str1)
"""
	abc
123一
"""

str2 = r'\tabc\n123\u4e00'
print(str2)
# \tabc\n123\u4e00

APPLICATION 路径:

path = r'C:\users\sprite\name\test\demo\a.txt'
print(path)

3.3 字符编码

(1)计算机存储原理:计算机保存数据的时候只能存数字,而且存的是数字的补码

RIGHT Example:

78 -> 01001110 -> 01001110 -> 01001110
-78 -> 11001110 -> 10110001 -> 10110010

(2)字符编码:为了能够让计算机保存文字符号,我们给每一个符号对应了一个固定的数字,在存储符号的时候就保存这个符号对应的数字,那么这个数字就是这个符号的编码值


3.4 编码表

保存符号和编码值对应关系的表

(1)ASCII码表:通过一个字节来对128个字符进行编码,里面的字符是美国通用的符号

数字在大写字母的前面、大写字母在小写字母的前面、大写字母和小写字母之间有间隙(A:65,a:97)

附:ASCII码

(2)Unicode编码表(python):包含了世界上所有的国家所有的民族的所有的语言的符号(万国码)

​ a. Unicode编码表是ASCII码表的扩展,它包含ASCII码表
​ b.中文编码值范围(16进制):4e00~9fa5


3.5 python使用编码值

(1)chr函数:chr(编码值):获取编码值对应的字符

RIGHT Example:

print(chr(97)) 				 # a
print(chr(65)) 				 # A

# 如果想要在程序中直接使用16进制数,数前必须加前缀'0x'、'0X'
print(chr(0x4e00)) 			 # 一

APPLICATION 打印所有中文:

count = 0
for x in range(0x4e00, 0x9fa5 + 1):
    count += 1
    print(chr(x), end=' ')
    if count % 30 == 0:
        print()

(2)ord函数:ord(字符):获取指定字符对应的编码值

RIGHT Example:

print(ord('余')) 			# 20313
print(ord('婷'))  			# 23159

# hex(十进制数):获取指定十进制对应的16进制
print(hex(20313), hex(23159))  # 0x4f59 0x5a77

3.6 编码字符

在字符串中用’\u4位的16进制数’来表示一个字符

RIGHT Example:

str1 = 'a\u0061'
print(str1)
# aa

str2 = 'a\u0061一\u4e00'
print(str2)
# aa一一

APPLICATION 判断是不是中文:

x = 'k'
print('\u4e00' <= x <= '\u9fa5')     # False
print('一' <= x <= '龥')              # False

小技巧:可以在输入法里面把"龥"添加个快捷输入


3.7 查:获取字符(符号)

列表获取元素的方法字符串都支持

(1)获取单个字符

RIGHT Example:

print(str1[1], str1[-1])          # e !

(2)切片

RIGHT Example:

str2 = 'hajsks'
print(str2[1:-1])				  # ajsk

(3)遍历

RIGHT Example:

str3 = 'abc123'
for x in str3:
    print(x, end=' ')          			# a b c 1 2 3 
    
for index in range(len(str3)):
    print(index, str3[index], end=';')  # 0 a;1 b;2 c;3 1;4 2;5 3;
    
for index, item in enumerate(str3):
    print(index, item, end=';')    		# 0 a;1 b;2 c;3 1;4 2;5 3;

3.8 相关操作


3.8.1 +、*

(1)字符串1+字符串2:将两个字符串合并成一个字符串

RIGHT Example:

str1 = 'hello'
str2 = 'python'
str3 = str1 + str2
print(str3)                             # hellopython

(2)字符串 * N、N * 字符串:将N个字符串合并成一个字符

RIGHT Example:

str1 = 'hello'
print(str1 * 3)                         # hellohellohello

3.8.2 比较大小

(1)基本概念:两个字符串比较大小比较的是第一对不相等的字符的编码值的大小

​ 两个字符比较大小就是比较两个字符的编码值的大小

RIGHT Example:

print('abc' < '1234567890') 			# False
print('abc' < 'Z234567890') 			# False
print('abc' < 'b234567890') 			# True

判断字符类型:

是否是数字:‘0’ <= x <= ‘9’
是否是小写字母:‘a’ <= x <= ‘z’
是否是字母:‘a’ <= x <= ‘z’ or ‘A’ <= x <= ‘Z’
是否是中文:‘一’<= x <= ‘龥’

(2)应用

APPLICATION 1 已知一个字符串,统计字符串中数字字符的个数:

str1 = 'abc1123你好110'
count1 = 0
for x in str1:
    if '0' <= x <= '9':
        count1 += 1
print(count1)                  			# 7

APPLICATION 2 已知一个字符串,提取字符串中所有的中文字符:

str1 = 'ab啊c1123你好110是-2=2'
str_chinese = ''
for x in str1:
    if '一' <= x <= '龥':
        str_chinese += x
print(str_chinese)            			# 啊你好是

3.8.3 in和not in

字符串1 in 字符串2:判断字符串2中是否包含字符串1(判断字符串1是否是字符串2的子串)

RIGHT Example:

print('a' in 'abc')  					# True
print('ab' in 'abc')  					# True

WRONG Example:

print('ac' in 'abc')  					# False

3.9 相关函数

(1)len(字符串):获取字符串长度

(2)str(数据):所有的数据都可以转换成字符串;转换的时候是在数据的打印值外面加引号

RIGHT Example:

num = 123
print(str(num)) 						# '123'

num = 1.23
print(str(num))  						# '1.23'

list1 = [10,20,30]
print(list1)         					# [10, 20, 30]
str(list1)								# '[10, 20, 30]'

list2 = ["abc",20,30]
print(list2)        		 			# ['abc', 20, 30]
str(list2)								# "['abc', 20, 30]"

list3 = ["abc",20,30,'ab']
print(list3)         				    # ['abc', 20, 30, 'ab']
str(list3)								# "['abc', 20, 30, 'ab']"

dict1 = {'a':10,"b":20}
print(dict1)   						 	# {'a': 10, 'b': 20}
# str(dict)    							# "{'a': 10, 'b': 20}"

(3)eval(字符串):获取指定字符串引号中的内容(去掉字符串的引号)

注意:这儿的字符串去掉引号以后必须是一个合法的表达式

RIGHT Example 1 去掉引号以后是合法的数据:

str的反向操作

result = eval('100')
print(result, result * 2, result + 10)  # 100

result = eval('"abc"')  				# "abc"
print(result, len(result))

result = eval('[10, 20, 30]')  			# "abc"
print(result)

WRONG 1 Example:

result = eval('[abc, 20, 30]')  # [abc, 20, 30]
print(result)  # 报错, NameError: name 'abc' is not defined

RIGHT Example 2 去掉引号以后是合法的表达式:

result = eval('100 + 200')
print(result)  							# 300

abc = 10
result = eval('abc')    				# 10
print(result)

nums = [10, 20, 30]
eval('nums.append(100)')
print(nums)         					# [10, 20, 30, 100]

3.10 相关方法

(1)字符串.join(序列):将序列中的元素用指定的字符串连接成一个新的字符串(序列中的元素必须全部是字符串)

RIGHT Example:

list1 = ['hello', 'world!', '您好', '世界']

result = ''.join(list1)
print(result)						# helloworld!您好世界

result = ','.join(list1)
print(result)						# hello,world!,您好,世界

APPLICATION 1 给字符串中间加空格:

str1 = 'hello'
result = ' '.join(str1)
print(result)						# h e l l o

APPLICATION 2 将nums中元素拼接成一个数字:

nums = [10, 20, 30, 4, 52]
result = ''.join([str(x) for x in nums])
print(result)						# 102030452

APPLICATION 3 将nums中所有数的个位数拼成一个数字字符串:

nums = [10, 20, 30, 4, 52]
result = ''.join([str(x) for x in nums])
print(result)						# 102030452

APPLICATION 4 将list1中所有的数字用’+'连接,并且计算它们的和:

list1 = [19, 'abc', True, 1.23, 8, 22.2, '环境']
result = '+'.join([str(x) for x in list1 if type(x) in (int, float)])
print(result, eval(result), sep='=')
# 19+1.23+8+22.2=50.43

(2)字符串1.split(字符串2):将字符串1中所有的字符串2作为切割点对字符串1进行切割,返回一个包含多个字符串的列表

RIGHT Example:

str1 = 'abc123hello123你好123Python'
result = str1.split('123')
print(result)						# ['abc', 'hello', '你好', 'Python']

# 注意:如果切割点在字符串开头或结尾,或者连续出现多个切割点,都会产生空串
str1 = '123abc123hello123你好123123Python123'
result = str1.split('123')
print(result)					# ['', 'abc', 'hello', '你好', '', 'Python', '']

字符串1.split(字符串2, N):将字符串1中前N个字符串2作为切割点对字符串1进行切割,返回一个包含多个字符串的列表

RIGHT Example:

str1 = 'abc123hello123你好123Python'
result = str1.split('123', 2)
print(result)						# ['abc', 'hello', '你好123Python']

(3)字符串1.replace(字符串2, 字符串3):将字符串1中所有的字符串2都替换成字符串3

RIGHT Example:

str1 = 'how are you? Im fine, Thank you!'
result = str1.replace('you', 'me')
print(result)						# how are me? Im fine, Thank me!

字符串1.replace(字符串2, 字符串3, N):将字符串1中前N个字符串2都替换成字符串3

RIGHT Example:

str1 = 'how are you? Im fine, Thank you!'
result = str1.replace('you', 'me', 1)
print(result)						# how are me? Im fine, Thank you!

(4)字符串.strip():去掉字符串前后的空白字符

RIGHT Example:

str1 = '       \t    \n       good good study      \n      '
print(str1.strip())					# good good study

字符串.strip(字符):去掉字符串前后的目标字符

str1 = '/good good study'
print(str1.strip('/'))				# good good study

(5)字符串1.count(字符串2):统计字符串1中字符串2出现的次数

RIGHT Example:

str1 = 'how are you? Im fine, Thank you!'
print(str1.count('you'))  			# 2
print(str1.count('a'))    			# 2

(6)maketrans(字符串1, 字符串2):通过字符串1和字符串2创建替换对应关系表

字符串.translate(对应关系表):按照对应关系表将字符串中的字符进行替换

RIGHT Example:

table = str.maketrans('abc', '123') # a-1, b-2, c-3
str1 = 'abcabc222zzzabc'
result = str1.translate(table)
print(result)						# 123123222zzz123

(7)字符串.center(长度, 字符):将指定字符串变成指定长度,不够的用指定字符填充,原字符放中间

字符串.ljust(长度, 字符):将指定字符串变成指定长度,不够的用指定字符填充,原字符放左边

字符串.rjust(长度, 字符):将指定字符串变成指定长度,不够的用指定字符填充,原字符放右边

字符串.zfill(长度, 字符) == 字符串.rjust(长度, ‘0’)

RIGHT Example:

str1 = 'abc'
print(str1.center(7, 'x'))			# xxabcxx
print(str1.ljust(7, 'x'))			# abcxxxx
print(str1.rjust(7, 'x')) 			# xxxxabc
print(str1.center(2, 'x'))			# abc

num = '123'
print(num.zfill(5))					# 00123

(8)字符串1.find(字符串2):获取字符串2在字符串1中第一次出现的位置,如果字符串2不存在,返回-1
字符串1.index(字符串2):获取字符串2在字符串1中第一次出现的位置,如果字符串2不存在,报错

字符串1.rfind(字符串2):从右往左找
字符串1.rindex(字符串2):从右往左找

RIGHT Example:

str1 = 'how are you? Im fine, Thank you!'
print(str1.find('you'))        	 	# 8
print(str1.index('you'))        	# 8

print(str1.find('yo u'))        	# -1
print(str1.index('yo u'))       	# 报错,ValueError: substring not found

print(str1.rfind('you'))        	# 28

(9)字符串.isdigit():判断字符串中的元素是否全是数字字符(即0到9)

字符串.numeric():判断字符串中的元素是否全是具有数字意义的字符

RIGHT Example:

str1 = '141241'
print(str1.isdigit())       	 	# True
print(str1.isnumeric())      		# True

str1 = '141241一①Ⅰ壹捌'
print(str1.isdigit())        		# False
print(str1.isnumeric())      		# True

(10)字符串.lower():将字符串中的大写改成小写

字符串.upper():将字符串中的小写改成大写

RIGHT Example:*

print('KFJdfdsf13'.lower())			# kfjdfdsf13
print('KFJdfdsf13'.upper())			# KFJDFDSF13

3.11 格式字符串


3.11.1 格式占位符创建字符串

语法:包含格式占位符的字符串 % (数据1, 数据2, 数据3, …)

注意;后面括号中的数据必须和前面字符串中的占位符一一对应

常用的格式占位符:

%s:字符串占位符,可以对应任何类型的数据

%d:整数占位符,可以对应任何数字

%f:浮点数占位符,可以对应任何数字

%.Nf:保留N位小数

RIGHT Example:*

str1 = '%s今年%d岁,月薪:%.2f元!' % (name, age, 12857.123)
print(str1)  						# 小明今年18岁,月薪:12857.12元!

price = 34.8

str2 = '价格:%s' % price
print(str2)  						# 价格:34.8

str2 = '价格:%d' % price
print(str2)  						# 价格:34

str2 = '价格:%f' % price
print(str2)  						# 价格:34.800000

3.11.2 f-string


3.11.2.1 基本用法

语法:在字符串最前面加f,就可以在字符串中通过’{表达式}'来提供字符串中变化的部分

RIGHT Example:*

name = "小明"
age = 18

str1 = '{name}'
print(str1)  						# {name}

str1 = f'{name}'
print(str1)  						# 小明

str1 = f'{name * 2}'
print(str1)  						# 小明小明

str1 = f'{name[1] * 3}'
print(str1)  						# 明明明

str1 = f'{name}=abc={age + 10}'
print(str1)  						# 小明=abc=28

score = [90, 89, 67]
str1 = f'{name}三门学科的分数:{str(score)[1:-1]}'
print(str1)  						# 小明三门学科的分数:90, 89, 67

3.11.2.2 高级用法

(1)控制小数位数的参数:{表达式:.Nf}

RIGHT Example:*

money = 11245
str1 = f'年薪:{money * 13:.2f}元'
print(str1)  						# 年薪:146185.00元

(2)显示百分比:{表达式:.N%}

RIGHT Example:*

rate = 0.87
str1 = f'班级及格率:{rate:.2%}'
print(str1)  						# 班级及格率:87.00%

(3)逗号显示金额:{表达式:,Nf}

RIGHT Example:*

money = 171245
str1 = f'年薪:{money * 13:,.2f}元'
print(str1)  						# 年薪:2,226,185.00元

(4)修改填充内容的长度:{表达式:字符>长度}、{表达式:字符<长度}、{表达式:字符^长度}

RIGHT Example:*

num = 23

str1 = f'py2202{num:0>4}'
print(str1)  						# py22020023

str1 = f'py2202{num:0<4}'
print(str1)  						# py22022300

str1 = f'py2202{num:0^4}'
print(str1)  						# py22020230

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Sprite.Nym

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

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

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

打赏作者

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

抵扣说明:

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

余额充值