Python full stack development, Day2, python development day2
Python basics 2 (basic data type) 1. Data
1. What is data?
X = 10, 10 is the data we want to store
2. Why are data of different types?
Data is used to indicate the State. Different States should be represented by different types of data.
3. Data Type
Number
String
List
Tuples
Dictionary
Set
Ii. Data Types
Number int
Numbers are mainly used for computing. If there are not many ways to use them, remember one of them:
# Bit_length () The minimum number of digits used in decimal format.
V = 11
Data = v. bit_length ()
Print (data)
Boolean bool
There are two boolean values: True and False. Is the correct response condition.
True 1 True.
False 0 False.
String str
Use "", '', ''', or """""". The portion in the middle is called a string.
PS: Even if a number is written in it, its data type is also a string
1. Index and slice of a string.
An index is a subscript, that is, the element of a string starts from the first index, and the initial index is 0, and so on.
a = 'ABCDEFGHIJK'print(a[0])print(a[3])print(a[5])print(a[7])
Execution output
A
D
F
H
Slice intercepts a string segment through the index (Index: Step) to form a new string (the principle is to ignore the ignore ).
A = 'abcdefghjk 'print (a [0: 3]) print (a [2: 5]) print (a [0:]) # default to the last print (a [0: -1]) #-1 is the last print (a []) # Add step size print (a [5: 0:-2]) # Add step size Reversely
Execution output
ABC
CDE
ABCDEFGHIJK
ABCDEFGHIJ
ACE
FDB
2. Common string methods.
# Captalize, swapcase, titlename = "ximenchunxue" print (name. capitalize () # print (name. swapcase () # case flip msg = 'egon say Hi' print (msg. title () # uppercase letters of each word
Execution output
Ximenchunxue
XIMENCHUNXUE
Egon Say Hi
# Content center, total length, blank space filled with name = "ximenchunxue" ret2 = name. center (20, "*") print (ret2)
Execution output
* *** Ximenchunxue ****
# Number of elements in a string. Name = "ximenchunxue" print (name [0: 10]) ret3 = name. count ("n",) # slable print (ret3)
Execution output
Ximenchunx
2
Explanation:
0, 10 indicates to extract 10 strings from left to right. The result is ximenchunx, and the letter n appears twice.
A2 = "hqw \ t1" ''' expandtabs () method converts the tab symbol ('\ t') in the string into a space, and the tab symbol (' \ t ') the default number of spaces is 8. By default, a tab key is changed to eight spaces. If there are less than eight characters in front of the tab, the total length is 8, if the length of the character before the tab key exceeds 8 to 16, then the number of characters is 16, and so on. '''Ret4 = a2.expandtabs () print (ret4)
Execution output
Hqw 1
A4 = "dkfjdkfasf54" # startswith determines whether to use... # endswith... end ret4 = a4.endswith ('jdk ',) # ignore tail print (ret4) # Return a Boolean value ret5 = a4.startswith ("kfj",) print (ret5)
Execution output
True
True
# Search for whether the elements in the string exist a4 = "dkfjdkfasf54" ret6 = a4.find ("fjdk",) print (ret6) # Return the index of the element found. If no index is found,-1 is returned.
Execution output
2
A4 = "dkfjdkfasf54" ret61 = a4.index ("fjdk",) print (ret61) # index of the returned element. If no index is found, an error is returned.
The following result is output, and an error is returned.
Traceback (most recent call last ):
File "E:/python_script/day1/test. py", line 3, in <module>
Ret61 = a4.index ("fjdk", 4,6)
ValueError: substring not found
# What is split to form a list. This list does not contain the split element. Ret9 = 'title, Tilte, atre ,'. split ('T') print (ret9) ret91 = 'title, Tilte, atre ,'. rsplit ('T', 1) print (ret91)
Execution output
['', 'I', 'le, Til ', 'e, A','re,']
['Title, Tilte, A','re, ']
# Format output res = '{}{}{}'. format ('egon', 18, 'male') print (res) res = '{1} {0} {1 }'. format ('egon', 18, 'male') print (res) res = '{name} {age} {sex }'. format (sex = 'male', name = 'egon', age = 18) print (res)
Execution output
Egon 18 male
18 egon 18
Egon 18 male
#stripname='*egon**'print(name.strip('*'))print(name.lstrip('*'))print(name.rstrip('*'))
Execution output
Egon
Egon **
* Egon
#replacename='alex say :i have one tesla,my name is alex'print(name.replace('alex','SB',1))
Execution output
SB say: I have one tesla, my name is alex
##### Is series name = 'jinxin123 'print (name. isalnum () # A string consists of letters or numbers (print (name. isalpha () # A string consists of only letters print (name. isdigit () # A string consists of only digits
Execution output
True
False
False
Yuanzu tupe
Tuples are called read-only lists, that is, data can be queried but cannot be modified. Therefore, string slicing is also applicable to tuples. Example: (1, 2, 3) ("a", "B", "c ")
List
A list is one of the basic data types in python. Other languages also have data types similar to a list. For example, an array in js is enclosed by []. Each element is separated by commas, in addition, it can store various data types such:
Li = ['Alex ', 123, True, (1, 2, 3, 'wusir'), [1, 2, 3, 'xiaoming ',], {'name ': 'Alex '}]
Compared with strings, a list not only stores different data types, but also stores a large amount of data. The 32-bit python has a limit of 536870912 elements, and the 64-bit python has a limit of 1152921504606846975 elements. In addition, the list is ordered, with index values, which can be sliced to facilitate the value.
Add
Li = [1, 'A', 'B', 2,3, 'a'] li. insert () # Add print (li) li according to the index. append ('aaa') # add to the last li. append ([1, 2, 3]) # add to the last print (li) li. extend (['q, a, W']) # iterative de-incrementing li. extend (['q, a, W', 'aaa']) li. extend ('A') li. extend ('abc') li. extend ('a, B, C') print (li)
Execution output
[55, 1, 'A', 'B', 2, 3, 'a']
[55, 1, 'A', 'B', 2, 3, 'A', 'aaa', [1, 2, 3]
[55, 1, 'A', 'B', 2, 3, 'A', 'aaa', [1, 2, 3], 'q,, w', 'q, a, W', 'aaa', 'A', 'A', 'B', 'C', 'A ',',', 'B', ',', 'C']
Delete
Li = [1, 'A', 'B', 2,3, 'a'] l1 = li. pop (1) # Delete by position. The returned value is print (l1) del li [] # Delete by position. You can also delete slices without returning values. Print (li) li. remove ('A') # Delete print (li) li. clear () by element # clear the list
Execution output
A
[1, 3, 'a']
[1, 3]
Change
li = [1,'a','b',2,3,'a']li[1] = 'dfasdfas'print(li)li[1:3] = ['a','b']print(li)
Execution output
[1, 'dfasdfas ',' B ', 2, 3, 'a']
[1, 'A', 'B', 2, 3, 'a']
Query
Slice to query, or loop to query.
Other operations
Count (number) (the number of times an element appears in the list ).
a = ["q","w","q","r","t","y"]print(a.count("q"))
Execution output
2
Index (the method is used to locate the index location of the first matching item of a value from the list)
a = ["q","w","r","t","y"]print(a.index("r"))
Execution output
2
Sort (the method is used to sort the list in the original position ).
Reverse (the method stores the elements in the list in reverse order ).
A = [2, 1, 3, 4, 5]. sort () # He does not return a value, so he can only print aprint (a). reverse () # He does not return any value, so he can only print aprint ()
Execution output
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
Dictionary dict
A dictionary is a unique ing type in python. It stores data in the form of key-value pairs. Python performs hash function operations on the key and determines the storage address of the value based on the calculation result. Therefore, the dictionary is unordered and the key must be hashable. Hash indicates that the key must be of an unchangeable type, such as numbers, strings, and tuples.
Dictionary is the most flexible built-in data structure type in python except for list exceptions. A list is a combination of ordered objects, and a dictionary is a collection of unordered objects. The difference between the two is that the elements in the dictionary are accessed by keys, rather than by offset.
Add
Dic = {'zhang ': 'K'} dic ['lil'] = ["a", "B", "c"] print (dic) # setdefault adds a key-value pair to the dictionary. If only the key is set, the corresponding value is none. However, if a key-value pair is set in the original dictionary, it will not be changed or overwritten. Dic. setdefault ('k', 'V') print (dic) # {'age': 18, 'name': 'jin', 'sex': 'male', 'K ': 'V'} dic. setdefault ('k', 'v1 ') # {'age': 18, 'name': 'jin', 'sex': 'male', 'K ': 'V'} print (dic)
Execution output
{'Lil': ['A', 'B', 'C'], 'zhang ': 'K '}
{'K': 'V', 'lil': ['A', 'B', 'C'], 'zhang ': 'K '}
{'K': 'V', 'lil': ['A', 'B', 'C'], 'zhang ': 'K '}
Delete
Dic = {'name': 'zhang ', 'age': 23} dic_pop = dic. pop ("a", 'default return value without key') # pop deletes key-value pairs based on the key and returns the corresponding value. If no key exists, the default return value print (dic_pop) is returned) del dic ["name"] # No return value. Print (dic) dic_pop1 = dic. popitem () # randomly delete a key-value pair in the dictionary. print (dic_pop1) is returned as the parent of the deleted key-Value Pair # ('name', 'jin ') dic_clear = dic. clear () # clear the dictionary print (dic, dic_clear) # {} None
Execution output
Default return value without key
{'Age': 23}
('Age', 23)
{} None
Change
Dic = {"name": "jin", "age": 18, "sex": "male"} dic2 = {"name": "alex", "weight ": 75} dic2.update (dic) # overwrite all the key-value pairs of dic (same overwrite, not added) to print (dic2) in dic2)
Execution output
{'Age': 18, 'name': 'jin', 'weight': 75, 'sex': 'male '}
Query
Dic = {"name": "jin", "age": 18, "sex ": "male"} value1 = dic ["name"] # The error print (value1) value2 = dic is not reported. get ("djffdsafg", "Default return value") # No set return value can be returned print (value2)
Execution output
Jin
Default Return Value
Other operations
Dic = {"name": "jin", "age": 18, "sex": "male"} item = dic. items () print (item, type (item) # dict_items ([('name', 'jin'), ('sex', 'male '), ('age', 18)]) <class 'dict _ items '> # This type is the dict_items type, and the iteratable keys = dic. keys () print (keys, type (keys) # dict_keys (['sex', 'age', 'name']) <class 'dict _ keys '> values = dic. values () print (values, type (values) # dict_values (['male', 18, 'jin']) <class 'dict _ values'> same as above
Execution output
Dict_items ([('sex', 'male'), ('age', 18), ('name', 'jin')]) <class 'dict _ items '>
Dict_keys (['sex', 'age', 'name']) <class 'dict _ keys '>
Dict_values (['male', 18, 'jin']) <class 'dict _ values'>
Dictionary Loop
dic = {"name":"jin","age":18,"sex":"male"}for key in dic: print(key)for item in dic.items(): print(item)for key,value in dic.items(): print(key,value)
Execution output
Age
Sex
Name
('Age', 18)
('Sex ', 'male ')
('Name', 'jin ')
Age 18
Sex male
Name jin
3. Others (for, enumerate, range)
For Loop: You can iterate the object Content in order.
Msg = 'I am the best' for item in msg: print (item) li = ['Alex ', 'Silver ange', 'goddess', 'egon ', 'White '] for I in li: print (I) dic = {'name': 'White', 'age': 18, 'sex ': 'man'} for k, v in dic. items (): print (k, v)
Execution output:
Me
Yes
Most
Good
Of
Alex
Silver horn
Goddess
Egon
Taibai
Name Too white
Age 18
Sex man
Enumerate: enumeration. For an iterable/traversed object (such as a list or string), enumerate forms an index sequence and obtains indexes and values at the same time.
Li = ['Alex ', 'Silver ange', 'goddess', 'egon', 'White '] for I in enumerate (li): print (I) for index, name in enumerate (li, 1): print (index, name) for index, name in enumerate (li, 100): # The default start position is 0. You can change the print (index, name)
Execution output:
(0, 'Alex ')
(1, 'Silver angular ')
(2, 'goddess ')
(3, 'egon ')
(4, 'white ')
1 alex
2 silver horn
3 goddess
4 egon
5 too white
100 alex
101 Silver horn
Goddess 102
103 egon
104 too white
Range: specifies a range to generate a specified number.
For I in range (): print (I) print ('=') for I in range (, 2): # Step Size print (I) print ('++') for I in range (10, 1,-2): # reverse step print (I)
Execution output
1
2
3
4
5
6
7
8
9
======
1
3
5
7
9
++
10
8
6
4
2