Python tour (3) - lists, tuples, dictionaries, sets, strings


In this article, I will learn the addition, deletion, modification, and query operations of lists, tuples, dictionaries, and collections, as well as simple integration of various operations on strings.

1. list

Both the number of elements in the list and the content of the elements can be changed. We can perform batch operations on data through lists. The following will talk about the creation, access and update of the list.

1.1 Create a list

The syntax for creating a list is as follows:

方法1:列表名 = [值1 , 值2 , 值3 , ...... , 值n]
方法2:使用list()函数创建,列表名=list(内容)
方法3:列表名 = [表达式 for 变量 in 序列]
  • A list is a flexible data type. The elements in a list can be of the same type or of different types; the data volume of elements in a list is also not fixed, and multiple elements can also be assigned to A single element, of course, can also be no element;
  • The elements in the list can be simple data types such as integer, floating point, and string, or combined data types such as lists, tuples, dictionaries, and sets;

Here's what I did to experiment with list creation:

#使用方法1:
>>> list1 = ["2018",19]
>>> list1
['2018', 19]
>>> list2 = []
>>> list2
[]
#使用方法2:
>>> list3 = list((1,2,3))
>>> list3
[1, 2, 3]
>>> list4 = list(range(1,6))
>>> list4
[1, 2, 3, 4, 5]
>>> list5 = list(list4)
>>> list5
[1, 2, 3, 4, 5]
>>> list6 = list(list3+list4)
>>> list6
[1, 2, 3, 1, 2, 3, 4, 5]
>>> list7 = list("Python程序设计")
>>> list7
['P', 'y', 't', 'h', 'o', 'n', '程', '序', '设', '计']
#使用方法3:
>>> list8 = [1/i for i in range(1,10)]
>>> list8
[1.0, 0.5, 0.3333333333333333, 0.25, 0.2, 0.16666666666666666, 0.14285714285714285, 0.125, 0.1111111111111111]

After some lists are not in use, we should delete the list in time to save storage space. We generally use del to delete the list. The syntax format is as follows:

del	列表名

The experiment is as follows:

>>> list1
['2018', 19]
>>> del list1
>>> list1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'list1' is not defined

1.2 Access list

The list is a sequence type, and the elements in it have a unique index value according to their position. We can access the specified element by accessing this index value. The syntax for accessing elements in a list is as follows:

列表名[索引值]
  • It should be noted here that python sets two sets of indexes for lists, which is different from C language. These two sets of indexes are: forward index and reverse index;
  • The index value of the forward index is incremented from 0, and the index value of the reverse index is decremented from -1.

Here's my experiment with accessing list elements:

>>> list1 = list(range(1,10))
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list1[4]
5
>>> list1[-5]
5
>>> list1[8]
9
>>> list1[-1]
9
>>> list1[0] = list1[-1]
>>> list1
[9, 2, 3, 4, 5, 6, 7, 8, 9]

Generally, when we access the elements in the list, we need to know how many elements are in the list. At this time, we need to use the len() function to automatically calculate the length of the list. Here are my experiments on this:

>>> source_list = list(range(1,50,2))
>>> num = 0
>>> for i in source_list:
...     num+=1
...
>>> print(num)
25
#使用len()函数可以达到以上代码的效果
>>> len(source_list)
25

1.3 Update list

After creating the list, I can add, delete, and modify elements in the list. The following is a brief description of these three operations, as well as a summary of some operations commonly used in lists.

1.3.1 Adding list elements

There are two syntax formats for adding list elements:

方法1:列表名.append(新增元素值)
方法2:列表名.insert(索引值,新增元素值)

The difference between the two methods mentioned above is as follows: the append() function is to append elements at the end of the list , while the insert() function can insert elements at the specified position of the list .
Here's how I increment a list using these two methods:

>>> list1 = []
>>> list1
[]
>>> list1.append([1,2])
>>> list1
[[1, 2]]
>>> list1.append("python")
>>> list1
[[1, 2], 'python']
>>> list1.insert(0,10)
>>> list1
[10, [1, 2], 'python']
#下面这几行需要注意,我指定的位置已经超过列表已有的序列,默认当成在列表末尾后增值
>>> list1.insert(4,8)
>>> list1
[10, [1, 2], 'python', 8]
>>> list1.insert(10,("python","程序"))
>>> list1
[10, [1, 2], 'python', 8, ('python', '程序')]
>>> list1.insert(5,10.98)
>>> list1
[10, [1, 2], 'python', 8, ('python', '程序'), 10.98]
#这里要注意的是append()函数每次只能向列表添加一个值
>>> list1 = []
>>> list1.append(1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: append() takes exactly one argument (3 given)

1.3.2 Delete List Elements

In the previous creation of the list, I have already mentioned a way to delete the list, that is, use del , but the above is to delete the entire list. If we only want to delete an element in the list, we can use the following two formats:

方法1:列表名.remove(元素值)
方法2:del 列表名[索引值]

Among them, we need to pay attention to the remove() function to delete the specified value from the list . If there are multiple values ​​in a list that are the same as the specified value, only the first value will be deleted.
Here are my experiments with these two methods:

>>> list1 = [1,2,3,4,5]
>>> list1
[1, 2, 3, 4, 5]
>>> list1.remove(1)
>>> list1
[2, 3, 4, 5]
>>> list1.insert(0,1)
>>> list1
[1, 2, 3, 4, 5]
>>> list1.append(1)
>>> list1
[1, 2, 3, 4, 5, 1]
>>> list1.remove(1)
>>> list1
[2, 3, 4, 5, 1]
>>> del list1[2]
>>> list1
[2, 3, 5, 1]
#这里我想验证如果列表中还有一个列表中也有1个值为1,这个值应如何删除
>>> list1.append([1,2,3])
>>> list1.append(1)
>>> del list1[-1]
>>> list1
[2, 3, 5, 1, [1, 2, 3]]
>>> del list1[3]
>>> list1.append(1)
>>> list1
[2, 3, 5, [1, 2, 3], 1]
>>> list1.remove(1)
>>> list1
[2, 3, 5, [1, 2, 3]]
#从下面这两个操作可以看出想将列表中列表的值删除,我们只可以用del
>>> list1.remove(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> del list1[-1][0]
>>> list1
[2, 3, 5, [2, 3]]

1.3.3 Modify list element value

For modifying the list element value, we can replace the existing element value at the specified position with the new element value in the form of an assignment statement, and its syntax format is as follows:

列表名[索引值] = 新元素值

The above method only modifies the element value corresponding to a given position . We can also modify the element value of a certain range in the following way.

列表名[i:j] = 元素值

Pay attention when using this method: if the number of new values ​​given is less than the number of element values ​​in the specified range, it is equivalent to deleting the element value; if the number of new values ​​given is more than the number of element values ​​in the specified range number, it is equivalent to increasing the element value.
Here are the experiments I conducted:

>>> list1 = ["张三",19,"2019837","学生","群众"]
>>> list1
['张三', 19, '2019837', '学生', '群众']
#元素值为列表中只有个字符串,表示要修改成的值是个列表
>>> list1[0]=["李四"]
>>> list1
[['李四'], 19, '2019837', '学生', '群众']
#直接输入一个字符串默认输入两个字符
>>> list1[-1:] = "团员"
>>> list1
[['李四'], 19, '2019837', '学生', '团', '员']
#修改列表中的数值时,需要用中括号括起来
>>> list1[-1:]=[10]
>>> list1
[['李四'], 19, '2019837', '学生', '团', 10]
>>> list1[-1:-2]=10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable
>>> list1[-1:-3]=[0]
>>> list1
[['李四'], 19, '2019837', '学生', '团', 0, 10]
>>> list1[1:3]=[18]
>>> list1
[['李四'], 18, '学生', '团', 0, 10]
>>> list1[:2]=["张无",20]
>>> list1
['张无', 20, '学生', '团', 0, 10]
>>> list1[:2]=["李留",21,"农民"]
>>> list1
['李留', 21, '农民', '学生', '团', 0, 10]

In the above experiment, we saw the following points:

  • The list name [i:j] represents the i-th element to the j-1th element, not including the j-th element;
  • In the list name [i:j], if i is omitted, the default list starts from subscript 0; if j is omitted, the default list ends at the last element, which includes the last element.

1.4 Other operations that will be used in the list

operator or operator or function name Functional description
+ concatenates two lists
* Duplicate connection list
in x is in the list, return True, otherwise False
not in Returns True if x is not in the list, otherwise False
len(list name) Returns the length of the list
max(list name) Returns the maximum element value in a list
min(list name) Returns the minimum element value in a list
sorted(list name, reverse=False/True) return a new sorted list
reversed(list name) Returns an iterator after performing reverse operations on the list, which needs to be converted to a list in the form of list(reversed(list name))
sum(list name) If the list is all numeric elements, return the accumulated sum

Here are my experiments with these operators or functions:

>>> list1 = [1,2,3,4]
>>> list2 = [5,6,7]
>>> list3 = list1+list2
>>> list3
[1, 2, 3, 4, 5, 6, 7]
>>> list4 = list2*3
>>> list4
[5, 6, 7, 5, 6, 7, 5, 6, 7]
>>> 3 in list1
True
>>> 10 in list2
False
>>> 10 not in list2
True
>>> len(list1)
4
>>> max(list1)
4
>>> min(list2)
5
>>> sorted(list4,reverse=False)
[5, 5, 5, 6, 6, 6, 7, 7, 7]
>>> sorted(list4,reverse=True)
[7, 7, 7, 6, 6, 6, 5, 5, 5]
>>> reversed(list1)
<list_reverseiterator object at 0x000001D691816550>
>>> list(reversed(list1))
[4, 3, 2, 1]
>>> sum(list2)
18

2. Tuples

A tuple can be regarded as a set of fixed lists. After the tuple is created, it cannot be modified, that is, the value of elements in the tuple cannot be modified, and elements cannot be added or deleted. Tuples are used to process batches of data that, once identified, do not change.

2.1 Create tuples

The syntax for creating a tuple is as follows:

方法1:元组名 = (值1,值2,值3,......,值n)
方法2:使用tuple()函数创建,元组名 = tuple(内容)
方法3:元组名 = (表达式 for 变量 in 序列)

Here's an experiment with tuple creation:

>>> tuple1 = (1,2,3,)
>>> tuple1
(1, 2, 3)
#只有一个元素的元组,元素值后面要跟有逗号,否则会被认为是一个表达式
>>> tuple2 = (1)
>>> tuple2
1
>>> type(tuple2)
<class 'int'>
>>> tuple2 = (1,)
>>> tuple2
(1,)
>>> type(tuple2)
<class 'tuple'>
>>> tuple2 = ("程序设计")
>>> tuple2
'程序设计'
>>> type(tuple2)
<class 'str'>
>>> tuple2 = tuple("程序设计")
>>> tuple2
('程', '序', '设', '计')
>>> tuple2 = ("程序设计", )
>>> tuple2
('程序设计',)
>>> type(tuple2)
<class 'tuple'>
#这里的输出与列表是不一样的,需要通过tuple()函数将值显化
>>> tuple3 = (i-1 for i in range(10))
>>> tuple3
<generator object <genexpr> at 0x0000016A5BA56F68>
>>> tuple(tuple3)
(-1, 0, 1, 2, 3, 4, 5, 6, 7, 8)

2.2 Accessing tuples

The access to tuple elements is similar to the access to list elements, and its syntax is as follows:

元组名[索引值]

The specific experiment is as follows:

>>> tuple1 = tuple(i+1 for i in range(20))
>>> tuple1
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
>>> tuple1[3]
4
>>> tuple1[1:5:2]
(2, 4)
>>> tuple1[-1:-10:-3]
(20, 17, 14)
>>> tuple1[-1:-3]  #
()
>>> tuple1[-1]
20
>>> tuple1[-1::-5]
(20, 15, 10, 5)
>>> tuple1[::-6]
(20, 14, 8, 2)
>>> tuple1[-1:-2]  #
()
>>> tuple1[:-3]
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17)
>>> tuple1[-1:-5]  #
()

2.3 Other operations

Experiment to see which functions can be used to mutate tuples:

#可以通过两个元组的相加来改变元组内部的元素数量
>>> tu1 = (1,2,5,3)
>>> tu2 = (1,7,23,0)
>>> tu3 = tu1+tu2
>>> tu3
(1, 2, 5, 3, 1, 7, 23, 0)
#用乘法来将元组中的元素值赋值多少遍
>>> tu4 = tu1*2
>>> tu4
(1, 2, 5, 3, 1, 2, 5, 3)
#元组中若全是数值,返回累加和
>>> sum(tu4)
22
>>> tu7 = ("小张",19,"大二")
>>> sum(tu7)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
#list()函数是会返回一个列表,并将元组变成列表,列表可进行对元素进行更新
>>> tu5 = list(tu1)
>>> tu5
[1, 2, 5, 3]
>>> tu5 = list(reversed(tu1))
>>> tu5
[3, 5, 2, 1]
>>> type(tu5)
<class 'list'>
>>> tu5.insert(10,0)
>>> tu5
[3, 5, 2, 1, 0]
#使用tuple()函数后,只是输出元组,但并未将列表变成元组
>>> tuple(tu5)
(3, 5, 2, 1, 0)
>>> type(tu5)
<class 'list'>
>>> tu5.insert(0,10)
>>> tu5
[10, 3, 5, 2, 1, 0]
#使用sorted()函数可以对元组进行排序
>>> tu6 = sorted(tu3,reverse=True)
>>> tu6
[23, 7, 5, 3, 2, 1, 1, 0]
>>> tu6 = sorted(tu3,reverse=False)
>>> tu6
[0, 1, 1, 2, 3, 5, 7, 23]

The operators or functions involved in tuples have similar functions to lists. The main difference between tuples and lists is that tuples are immutable, while lists can be changed.

3. Dictionary

Since we use lists or tuples to find or read a certain data element in a batch of data, we need to know the index value of the element, but remembering the index value is not an easy task. Through dictionaries, we can look up or read information in bulk data through keywords .

3.1 Create a dictionary

The syntax for creating a dictionary is as follows:

方法1:字典名 = {键1:值1,键2:值2,...,键n:值n}
方法2:使用dict()函数来创建字典,字典名 = dict(内容)
方法3:推导式创建字典

Here are some experiments I conducted:

>>> dict1 = {
    
    "数学":89,"语文":79,"英语":80}
>>> dict1
{
    
    '数学': 89, '语文': 79, '英语': 80}
>>> dict2 = dict(["数学",78])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot convert dictionary update sequence element #1 to a sequence
>>> dict2 = dict([["数学",78]])
>>> dict2
{
    
    '数学': 78}
>>> dict3 = dict([["数学",80],["英语",79]])
>>> dict3
{
    
    '数学': 80, '英语': 79}
>>> dict4 = {
    
    i:i*i for i in range(10,30,4)}
>>> dict4
{
    
    10: 100, 14: 196, 18: 324, 22: 484, 26: 676}

3.2 Accessing the dictionary

The syntax for accessing a dictionary is as follows:

字典名[键]

Unlike lists and tuples, dictionaries are unordered sequences in which elements do not have corresponding index values. Here's my experiment with access to dictionary elements:

>>> dict1 = {
    
    "数学":88,"英语":78,"语文":89,"计算机":90}
>>> dict1
{
    
    '数学': 88, '英语': 78, '语文': 89, '计算机': 90}
>>> dict1[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 1
>>> dict1["数学"]
88

3.3 Updating the dictionary

The dictionary can be updated by adding dictionary elements, deleting dictionary elements, modifying element values, deleting dictionaries, etc.

3.3.1 Adding elements and modifying element values

There are several formats for adding dictionary elements and modifying element values ​​in the dictionary:

方法1:字典名[键] = 值
方法2:使用setdefault()函数,即字典名.setdefault(键,值)
方法3:使用update()函数,即字典名1.update(字典名2)
  • The first method is to modify or add elements in the dictionary by using assignment statements;
  • In the first two methods, if the specified "key" is not found in the dictionary, the "key-value" pair will be added to the dictionary, and if the specified "key" can be found, the corresponding "value" will be modified ;
  • The third method is to merge dictionaries. If the "keys" of the two dictionaries are not the same, add the elements in dictionary 2 to dictionary 1. If they are the same, modify dictionary 1 with the value in dictionary 2. The corresponding element value in .

Here are my experiments with the three formats:

>>> dict1 = {
    
    "数学":88,"英语":78,"语文":89,"计算机":90}
>>> dict1
{
    
    '数学': 88, '英语': 78, '语文': 89, '计算机': 90}
>>> dict1["物理"] = 79
>>> dict1
{
    
    '数学': 88, '英语': 78, '语文': 89, '计算机': 90, '物理': 79}
>>> dict1["数学"] = 80
>>> dict1
{
    
    '数学': 80, '英语': 78, '语文': 89, '计算机': 90, '物理': 79}
>>> dict1.setdefault("统筹",29)
29
>>> dict1
{
    
    '数学': 80, '英语': 78, '语文': 89, '计算机': 90, '物理': 79, '统筹': 29}
>>> dict1.update(dict2)
>>> dict1
{
    
    '数学': 80, '英语': 10, '语文': 89, '计算机': 90, '物理': 79, '统筹': 29, '电工': 77}

3.3.2 Delete element and delete dictionary

There are three ways to delete dictionary elements and delete dictionaries:

方法1:del 字典名[键] / del 字典名
方法2:del(字典名[键])          #此处是使用del()函数的方法
方法3:字典名.pop(键,值)

The experiment is as follows:

>>> dict1 = {
    
    "name":"李四","sex":"男","age":19}
>>> dict1
{
    
    'name': '李四', 'sex': '男', 'age': 19}
>>> del dict1["name"]
>>> dict1
{
    
    'sex': '男', 'age': 19}
>>> del dict1
>>> dict1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dict1' is not defined
>>> dict1 = {
    
    "name":"张三","sex":"男","age":29}
>>> dict1
{
    
    'name': '张三', 'sex': '男', 'age': 29}
>>> del(dict1["name"])
>>> dict1
{
    
    'sex': '男', 'age': 29}
>>> dict1.pop("sex","男")
'男'
>>> dict1
{
    
    'age': 29}
>>> dict1.setdefault("name","李四")
'李四'
>>> dict1
{
    
    'age': 29, 'name': '李四'}
>>> dict1.pop("name","张三")
'李四'
>>> dict1
{
    
    'age': 29}
>>> del(dict1)
>>> dict1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'dict1' is not defined

3.4 Functions and methods for other operations

function/method Functional description
dictionary name.keys() Returns all "keys" in the specified dictionary
dictionary name.values() Returns all "values" in the specified dictionary
dictionary name.items() Returns all "key-value" pairs in the specified dictionary
DictionaryName.get(key, default) If there is a "key" identical to "key", return the corresponding value, otherwise return the default value
dictionary name.popitem() Randomly take a "key-value" pair from the dictionary, return it as a tuple (key, value), and delete the "key-value" pair
dictionary name.clear() Deletes all "key-value" pairs of the specified dictionary, making it an empty dictionary
key in dictionary name If the "key" exists, return True, otherwise return False

The following are experiments on the above functions:

>>> dict1 = {
    
    "数学":88,"语文":79,"英语":77,"计算机":89}
>>> dict1
{
    
    '数学': 88, '语文': 79, '英语': 77, '计算机': 89}
>>> dict1.keys()
dict_keys(['数学', '语文', '英语', '计算机'])
>>> dict1.values()
dict_values([88, 79, 77, 89])
>>> dict1.items()
dict_items([('数学', 88), ('语文', 79), ('英语', 77), ('计算机', 89)])
>>> dict1.get("数学",10)
88
>>> dict1.get("物理",10)
10
>>> "数学" in dict1
True
>>> "物理" in dict1
False
>>> dict1.popitem()
('计算机', 89)
>>> dict1
{
    
    '数学': 88, '语文': 79, '英语': 77}
>>> dict1.clear()
>>> dict1
{
    
    }

4. Collection

4.1 Create collection

There are two ways to create collections:

方法1:集合名 = {元素1, 元素2, ... ,元素n}
方法2:集合名 = set(列表或元组)

Here's an experiment with two methods of creating collections:

>>> set1 = {
    
    0,1,2,3,4}
>>> set1
{
    
    0, 1, 2, 3, 4}
>>> set2 = {
    
    ("语文",80),("数学",88),("英语",79)}
>>> set2
{
    
    ('语文', 80), ('英语', 79), ('数学', 88)}
>>> set3 = set([1,2,3,4])
>>> set3
{
    
    1, 2, 3, 4}
>>> set4 = set((2,3,4,5))
>>> set4
{
    
    2, 3, 4, 5}
>>> set5 = set(i for i in range(10))
>>> set5
{
    
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
#集合与列表、元组的不同,有重复元素只保留一个元素
>>> set6 = set([1,1,1,3,2,2,3])
>>> set6
{
    
    1, 2, 3}
>>> list1 = list((1,1,1,3,2,2,3))
>>> list1
[1, 1, 1, 3, 2, 2, 3]
>>> tuple1 = tuple((1,1,1,3,2,2,3))
>>> tuple1
(1, 1, 1, 3, 2, 2, 3)

4.2 Accessing collections

To access a collection, elements cannot be accessed by using index values ​​like lists and tuples, nor can elements be accessed by "keys" like dictionaries. Collections can only be accessed by traversing all elements .
Here's a small example of my attempt at accessing collection elements:

score_set = {
    
    ("语文",80),("英语",89),("数学",90)}
print("数学成绩是多少:")
for item in score_set:
	if (item[0] == "数学"):
		print(item[1])
	else:
		continue

4.3 Updating collections

4.3.1 Adding elements

There are two ways to add elements to a collection:

方法1:集合名.add(值)
方法2:集合名.update(集合2)

Here's an experiment with both methods:

>>> set1 = {
    
    2,3,4,5}
>>> set1
{
    
    2, 3, 4, 5}
>>> set1.add(0)
>>> set1
{
    
    0, 2, 3, 4, 5}
#add()函数中只能放一个元素
>>> set1.add(1,6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)
>>> set1.add(1)
>>> set1
{
    
    0, 1, 2, 3, 4, 5}
>>> set1.add(10)
>>> set1
{
    
    0, 1, 2, 3, 4, 5, 10}
>>> set1.add([7,8])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> set1.add((7,8))
>>> set1
{
    
    0, 1, 2, 3, 4, 5, 10, (7, 8)}
#下面是对update()函数的实验
>>> set1 = {
    
    1,2,3,4}
>>> set2 = {
    
    0,1,2,6,7}
>>> set1.update(set2)   #等价于set1.update({0,1,2,6,7})
>>> set1
{
    
    0, 1, 2, 3, 4, 6, 7}
>>> set1.add(10)
>>> set1
{
    
    0, 1, 2, 3, 4, 6, 7, 10}
>>> set2.update(set1)
>>> set2
{
    
    0, 1, 2, 3, 4, 6, 7, 10}

4.3.2 Deleting elements

There are four ways to delete elements from a collection:

方法1:集合名.remove(元素值)
方法2:集合名.discard(元素值)
方法3:集合名.pop()
方法4:集合名.clear()

Experiment with the four methods of removing elements above:

>>> set1 = set(i for i in range(15))
>>> set1
{
    
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}
#若在remove()函数中设定的值是集合中没有的值会报错
>>> set1.remove()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: remove() takes exactly one argument (0 given)
>>> set1.remove(19)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 19
>>> set1.remove(8)
>>> set1
{
    
    0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14}
#discard()函数与remove()函数作用相类似,但若给出的值是集合中没有的,并不会报错
>>> set1.discard()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: discard() takes exactly one argument (0 given)
>>> set1.discard(19)
>>> set1
{
    
    0, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14}
>>> set1.discard(3)
>>> set1
{
    
    0, 1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14}
#pop()函数是从集合中随机删除一个元素,这个删除的元素会被作为函数的返回值
>>> set1.pop()
0
>>> set1
{
    
    1, 2, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14}
>>> set1.pop()
1
#clear()函数将集合中的所有元素删除,得到空集合
>>> set1.clear()
>>> set1
set()

5. String

There are generally two ways to define a string of strings, that is, direct assignment and input with the input() function; and there are two ways to access strings, namely, indexing and slicing. These two ways are also mentioned in the access list However, the following mainly talks about strings from two aspects, that is, the operation and format setting of strings.

5.1 String operations

In this section, I will understand the methods used in strings from three aspects: string operators, string operation functions, and string processing methods.

5.1.1 String operators

operator Functional description
+ str1+str2: concatenation of two strings
* n *str1: the string itself is concatenated n times
in str1 in str2: str1 is a substring of str2
not in str1 not in str2: str1 is not a substring of str2
<,<=,>,>=,==,!= str1<str2: str1 is less than str2; others like this

Experiment with the five types of operators mentioned above:

>>> str1 = "12345"
>>> str2 = "012"
>>> str1+str2
'12345012'
>>> str1*2
'1234512345'
>>> str1 in str2
False
>>> str2 in str1
False
>>> str1 not in str2
True
>>> str2 = "345"
>>> str2 not in str1
False
>>> str2 in str1
True
>>> str1<str2
True
>>> str1<=str2
True
>>> str1 == str2
False
>>> str1 != str2
True

5.1.2 String operation functions

Function name Functional description
len(string) len(str1): returns the length of the string str1
str(value) str(x): returns the string corresponding to x, with positive and negative signs
chr (encoded value) chr(n): returns the character corresponding to the encoded value n
ord(character) ord©: returns the coded value corresponding to the character c

The following is an experiment performed on the four functions mentioned above:

>>> str1 = "12345"
>>> str2 = "012"
>>> len(str1)
5
>>> len(str2)
3
>>> str(9876)
'9876'
>>> str(-67)
'-67'
>>> str(+12)
'12'
>>> chr(1)
'\x01'
>>> chr(65)
'A'
>>> ord('C')
67
>>> ord('!')
33

5.1.3 String processing methods

Python is an object-oriented programming language, which encapsulates each data type into a class, and provides several functions in the class, which are called "methods". The following are common processing methods for built-in strings.

method name (function name) Functional description
str1.lower() Convert all English characters in str1 to lowercase as the return value
str1.upper() Convert all English characters in str1 to uppercase as the return value
str1.capitalize() Convert the first letter in str1 to uppercase as the return value
str1.title() Convert the first letter of each word in str1 to uppercase as the return value
str1.replace(s1,s2,n) Replace the s1 substring in str1 with s2, if no n option is given, replace all s1 substrings; if there is n option, replace the first n s1 substrings
str1.split(sep,n) Decompose str1 into a list, sep is the separator (the default is a space), n is the number of substrings decomposed, and the default is all substrings
str1.find(str2) If str2 is a substring of str1, return the starting position of str2 in str1, otherwise return -1
str1.count(str2) Returns the number of occurrences of str2 in str1
str1.isnumeric() If the characters in str1 are all numeric characters, return True, otherwise return False
str1.isalpha() If the characters in str1 are all letters or Chinese characters, return True, otherwise return False
str1.isupper() If the letters in str1 are all uppercase, return True, otherwise return False
str1.islower() If the letters in str1 are all lowercase, return True, otherwise return False
str1.format() Format str1

Here is the experiment:

>>> str1 = "PYTHon"
>>> str1.lower()
'python'
>>> str1
'PYTHon'
>>> str1.upper()
'PYTHON'
>>> str1
'PYTHon'
>>> str1 = "python"
>>> str1.capitalize()
'Python'
>>> str1
'python'
>>> str1 = "learn python"
>>> str1.title()
'Learn Python'
>>> str1
'learn python'
>>> str1.replace('n','o',1)
'learo python'
>>> str1
'learn python'
>>> str1.replace('n','o')
'learo pythoo'
>>> str1
'learn python'
>>> str1 = "We are learning python"
>>> str1.split(' ',2)
['We', 'are', 'learning python']
>>> str1.split()
['We', 'are', 'learning', 'python']
>>> str1.split('e')
['W', ' ar', ' l', 'arning python']
>>> str1.find('are')
3
>>> str1.find('Are')
-1
>>> str1.count('e')
3
>>> str1.isnumeric()
False
>>> str1.isalpha()
False
>>> str1.isupper()
False
>>> str1.islower()
False
>>> str1.format()
'We are learning python'

5.2 Formatting of strings

There are two ways to control the data output format in Python, one is the % format setting method, and the other is the format() format setting method.

5.2.1 %Format setting method

Learn this formatting method by experimenting:

#整数输出
>>> print("输出一个十进制数:%d"%20)
输出一个十进制数:20
>>> print("输出一个十进制数:%d" ,%20)
  File "<stdin>", line 1
    print("输出一个十进制数:%d" ,%20)
                         ^
SyntaxError: invalid syntax
>>> print("输出一个八进制数:%o"%20)
输出一个八进制数:24
>>> print("输出一个八进制数:%3o"%20)
输出一个八进制数: 24
>>> print("输出一个八进制数:%.3o"%20)
输出一个八进制数:024
>>> print("输出一个十六进制数:%x"%20)
输出一个十六进制数:14
#浮点数输出
>>> print("输出一个浮点数:%f"%12.13)  #保留小数点后面六位有效数字
输出一个浮点数:12.130000
>>> print("输出一个浮点数:%.1f"%12.13)
输出一个浮点数:12.1
>>> print("输出一个浮点数:%3.1f"%12.13)
输出一个浮点数:12.1
>>> print("输出一个浮点数:%e"%12.13)  #保留小数点后面六位有效数字,指数形式输出
输出一个浮点数:1.213000e+01
>>> print("输出一个浮点数:%.3e"%12.13)
输出一个浮点数:1.213e+01
>>> print("输出一个浮点数:%g"%12.13)  #在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
输出一个浮点数:12.13
>>> print("输出一个浮点数:%g"%120987.123456)
输出一个浮点数:120987
>>> print("输出一个浮点数:%g"%12.123456)
输出一个浮点数:12.1235
>>> print("输出一个浮点数:%.3g"%12.123456)
输出一个浮点数:12.1
#字符串输出
>>> print('%s'%'hello world')
hello world
>>> print('20%s'%'hello world')
20hello world
>>> print('%20s'%'hello world')
         hello world
>>> print('%-20s'%'hello world')
hello world
>>> print('%.2s'%'hello world')
he
>>> print('%10.2s'%'hello world')
        he

5.2.2 format() format setting method

The syntax for using the format() method is as follows:

模板字符串.format(参数表)
其中模板字符串是由字符和一系列槽(用一对大括号表示)组成

Examples are as follows:

>>> print("{}乘以{}等于{}".format(16,3,16*3))
16乘以3等于48

上述例子是对format()格式输出的一种简单例子,为了能够更精准、更严格地输出数据,模板字符串中的槽中可以写入格式控制信息,其格式如下:

{参数序号:格式控制标记}.format(参数表)

格式控制标记可以参考下表:

格式标记 含义
填充 用于满足输出宽度要求需要(参数宽度不满足输出宽度要求)填充的单个字符,默认是空格
对齐 <表示控制左对齐,>表示控制右对齐,^表示控制居中对齐
宽度 设定槽对应的参数值的输出宽度
, 数值的千位分隔符,便于阅读
.精度 浮点数小数部分的保留位数/字符串的最大输出长度
类型 对于整数可选用符号c和d,对于浮点数可选用符号e、E、f、%。其中:c表示输出整数对应的Unicode字符;d表示整数的十进制形式;e表示输出浮点数对应的小写字母e的指数形式;E表示输出浮点数对应的大写字母E的指数形式;f表示输出浮点数的标准浮点形式;%表示输出浮点数的百分比形式

实验如下:

>>> print("{:-^30,}".format(123456789))
---------123,456,789----------
>>> print("{:}".format(6789))
6789
>>> print("{2:*>4}{1:->4}{0:@>4}".format(45678,9876,23451))
23451987645678
>>> print("{2:*>8}{1:->10}{0:@>8}".format(45678,9876,23451))
***23451------9876@@@45678
>>> print("{:5d}".format(32))
   32
>>> print("{:5c}".format(65))
    A
>>> print("{:5d}".format(65))
   65
>>> print("{:10.2f}".format(567.8765))
    567.88
>>> print("{:10.2e}".format(567.8765))
  5.68e+02
>>> print("{:10.2E}".format(567.8765))
  5.68E+02
>>> print("{:10.2%}".format(567.8765))
 56787.65%

Guess you like

Origin blog.csdn.net/qingtian_111/article/details/102734267