• python3.8.8

• jupyter-lab

# Data type acquisition method

• type(): returns the data type of the specified value
```type("11")
output: str
```
• isintance(): judge whether the incoming value is of the specified type
```isinstance('Python Hello', str)
output:True
```

# Basic data types (6)

1 int: number
2 str: String
3: List
4 tuple: tuple
5 sets: Set
6 dict: Dictionary

```print("1 %s"% type(1))
print("'11' %s"% type("1"))
print("[1] %s"% type([1]))
print("{'1':1} %s"% type({'1':1}))
print("(1,2) %s"% type((1,2)))
print("{1,2} %s"% type({1,2}))
output:
1 <class 'int'>
'11' <class 'str'>
[1] <class 'list'>
{'1':1} <class 'dict'>
(1,2) <class 'tuple'>
{1,2} <class 'set'>

```

## Immutable data type

Immutable data types include int (number), str (string), tuple (tuple), float (floating point), Boolean (Boolean)

### Numeric (int) type operation

#### Data type conversion

int(x): converts x to an integer.

float(x): converts x to a floating point number.

complex(x, y): convert x to a complex number. The real part is X. when y is not passed, the imaginary part is 0.

#### Operator '+ - * / / / /% * * *'

Note that "/" always returns a floating-point type

```type(8 / 6 )
output:
float

```

"/ /": returns the result of division rounded down,

Note: the return value is also related to the denominator. If the denominator is floating point, the return value is also floating point

```17 % 3
output: 2
```

'%': return remainder

```17 // 3
output:5
```

**: power operation

#### abs(x)

Returns the absolute value of a number

```abs(-1)
output:1
```

#### math.xxx

• math.ceil(x): returns the ascending integer of a number

• math.exp(x): returns the X-Power of e

• math.floor(x): returns the rounded down integer of a number

• math.fabs(x): returns the absolute value of a number

• math.log(x, y): returns the logarithm of X with y as the base

• math.log10(x): returns the logarithm based on 10

• math.pi: Pi

• math.e: natural constant

• math.modf(x): returns the integer part and decimal part of X. The numerical symbols of the two parts are the same as X. the integer part is represented by floating point.

```import math
x = 2.22
print(math.ceil(x))#Returns the up integer of a number
output:3

x = 2
print(math.exp(x))#Returns the x-Power of e
output:7.38905609893065

x = 2.22
print(math.floor(x))#Returns the rounded down integer of a number
output:2

x = -1
print(math.fabs(x))#Returns the absolute value of a number
output:1.0

x,y =100,10
print(math.log(x,y))#Returns the logarithm of x based on y
output:2.0

x = 100
print(math.log10(x))#Returns the logarithm based on 10
output:2.0

print(math.pi)#PI
output:3.141592653589793

print(math.e)#Natural constant
output:2.718281828459045
print(math.modf(2.1) #Returns the integer part and decimal part of x. The numerical symbols of the two parts are the same as x. the integer part is represented by floating point.
output:(0.10000000000000009, 2.0)
```

#### max(x,y,z),min(x,y,z)

Calculate the maximum / minimum number in x,y,z

```max(1,2,3)
output:3
min(1,2,3)
output:1
```

#### pow(x,y)

Calculate the value after x**y operation

```pow(10,2)
output:100
```

#### sqrt()

sqrt(x) returns the square root of the number X

```sqrt(100)
output:10
```

#### round(x[,n])

round returns the rounding of the floating point number x

See specification output section

#### Generate random number

See random numbers

### String (str) operation

#### Data type conversion

str() converts the specified value to a string type.

```str(1.222)
output:'1.222'
```

#### eval()

To convert a string into a valid python expression or calculation result, you can also convert data types:

```# Convert to expression, 3 to int
eval("1+2")
output:3
# Conversion of data types
res = eval("[1,2]")
type(res)
output:list
```

#### Returns a specific format (center, case, fill)

• str.capitalize()

Returns a string whose first letter is uppercase and the rest is lowercase

```cap = 'pyThoN'.capitalize()
pirnt(cap) # 'Python'
```
• str.center(width,fillchar)

Returns a centered string with a specified length and width. The empty part is filled with the characters specified by fillchar. Fillchar defaults to space

Note: fillchar only supports one character

```center= 'Python_demo'.center(25, "-")
print(center)
output:
'-------Python_demo-------'

```
• str.lower() &str.upper()

Str.lower() & str.upper() converts the specified string to lowercase / uppercase

```'PytHON'.lower()
output:python
```
• str.title()

title() returns the initial capital of each word in the string

```'python'.title()
output:'Python'
```
• str.ljust() & str.rjust()

Str.ljust (width, fillchar) & str.rjust (width, fillchar) implements left-right alignment of strings of a specified width

```ljust_str = 'Python_demo'.ljust(15, "!")
output: 'Python_demo!!!!'

```

#### Statistics, search, fixed-point search

• str.count()

str.count(sub, start, end) returns the number of times sub appears in str. you can specify the range through [start, end]. If not specified, the whole string will be found by default.

```name = 'psddaaa python'
name.count('a'), name.count('p', 1)
output:(3,1)

```
• str.find() & str.rfind()

find() scans the string from left to right and returns the subscript of the sub for the first time. You can specify the range through [start, end]. If not specified, the whole string will be found by default. If no string is found at last, - 1 is returned.

rfind starts scanning from right to left, and the result is consistent with find

```name = 'Python'

name.find('Py'), name.find('Py', 1)
output:(0,-1)
```
• str.index() & str.rindex()

```name = 'Python'
name.index('Py', 0)
output: 0

```

#### Judgment (alphanumeric uppercase and lowercase Chinese characters, beginning and end of spaces)

• str.isalnum()

isalnum() determines whether all characters in the string are letters / Chinese characters / numbers, True or False, and the empty string returns False

```'Python String 12'.isalnum()
output: True

```
• str.isalpha()

isalpha() determines whether all characters in the string are letters / Chinese characters. It is True or False. An empty string returns False

```'Python character string'.isalpha()
output: True

```
• str.isdigit()

isdigit() determines whether all characters in the string are numbers (Unicode number, byte number (single byte), full angle number (double byte), Roman number), yes, no, False, and the empty string returns False

• str.isspace()

The string contains only spaces (\ n line feed, \ r carriage return, \ f page feed, \ t horizontal tab, \ v vertical tab). Yes, no, False. An empty string returns False

```'\n\r\f\t\v'.isspace()
output:True
```
• str.startswith() & str.endswith

Startswitch (prefix [, start [, end]]) checks whether the string starts with the specified substr. If it is True or False, the empty string will report an error. If start and end are specified, it will be checked within the specified range.

```startswith_str = 'Python_demo'
startswith_str.startswith('thon', 2) #Detect from the 3rd character
output:True
```
• str.istitle()

istitle() determines whether the string satisfies the capitalization of the first letter of each word. It is True, no False, and the empty string returns False

• str.isupper()& str.islower()

Str.isupper() & str.islower() determines whether all case sensitive characters in a string are in uppercase / lowercase

Note: an empty string or case sensitive character of a string returns False

#### Cutting, dividing, assembling

• str.lstrip() & str.rstrip() & str.strip()

str.lstrip() will intercept the left side of the string according to the specified character. If no default space is specified, enter \ r\n\t

```name = '+++Python+++'
name.lstrip('+')
output: 'Python+++'

```

str.strip() intercepts the characters specified on both sides of the string

• str.join(iter)

join(iterable) combines all elements in iterable (which must be strings) into a new string with the specified string as the separator.

```"---".join(["p","y","t"])
output:'p---y---t'
tip:
"---".join(["p"]) # Delimiters are not added when there is only one element
output:'p'
```
• str.split() & str.splitlines()

Str.split (sep = none, maxplit = - 1) use sep as the separator to split and return the list. The maximum number of times maxplit splits from left to right

```split_str = 'P y t h o n111'
split_str.split(maxsplit=2)
output:['p','y','t h o n111']
```

str.splitlines returns a list of lines in a string, separated by lines ('\ r', \ n ',' \ r\n '), and returns a separated list. It has only one parameter, keepends, which indicates whether to keep line breaks in the result. False (default) does not keep them, and True keeps them

```split_str = 'P\ny\r t hon'
split_str.splitlines(keepends=True)
output:['P\n', 'y\r', ' t hon']
```

### Tuple operation

#### tuple()

tuple() converts iteratable objects into tuples

```tuple([0,1,2]) + tuple(range(3)) + tuple({0,1,2}) + tuple('012')
output:(0, 1, 2, 0, 1, 2, 0, 1, 2, '0', '1', '2')
```

## Variable data type

Variable types include list, dict and set

### List operation

#### list()

list() turns iteratable objects into lists.

```list((0,1,2)) + list({0,1,2}) + list('012')
output:[0, 1, 2]
```

• list.append(): append write and add elements at the end
```lst = ['Python', 'Java']
lst.append('C')
lst
output: ['Python', 'Java', 'C']

```
• List. Extend(): expand the list, add iteratable objects at the end of the list, and pay attention to the addition of dictionaries and collections
```lst = ['Python']
lst.extend('123')
output:['Python','1', '2', '3']
# Append set
lst = ['Python']
lst.extend({1,2,3})
lst
output:['Python','1', '2', '3']
# Appending a dictionary will only append the key to the end
lst = ['Python']
lst.extend({1: 'b', 2: 'a'})
lst
['Python', 1, 2]

```
• list.insert(index,object): inserts the specified object into the index position. When the index is greater than the length of the list, the element will be added to the end
```lst = ['Python', 'Java', 'C']
lst.insert(1, 'C++')
lst
output: ['Python', 'C++', 'Java', 'C']

```

#### Delete

• list.pop(): removes the element at the specified position and returns the value of the deleted element. By default, the last element is removed. If the length is exceeded, an error will be reported.
```lst = ['P','y','t','h','o','n']
lst.pop(1), lst
output: ('y',['P','t','h','o','n'])

```
• list.remove(value): delete the value that appears for the first time in the list. If there is no return value, modify the list directly. If the value does not exist, an error will be reported.

• list.clear(): remove all elements in the list without return value. The list is []

#### Change (assignment sort)

• list.reverse(): reverse the order of the list itself
```lst = [1, 5, 9, 2]
lst.reverse()
lst
output: [2, 9, 5, 1]

```
• list.sort(key, reverse): sort the list in a specific way, modify the original list, and the order will not change due to sorting when the elements are equal.

key: Specifies that each element in the iteratable object is sorted according to this function, which is usually used with lambda.

reverse: False is in ascending order and True is in descending order

```lst = [{"id":"2"},{"id":"5"},{"id":"3"}]
lst.sort(key=lambda x:x["id"],reverse=False)
output:
[{'id': '2'}, {'id': '3'}, {'id': '5'}]

```

#### check

• list.index(value,start,stop): returns the index of the first element in the list that matches value.

• list.count(value): returns the number of times value appears in the list. If there is no value, it returns 0

#### list.copy() # deep copy shallow copy

Shallow copy usually only copies the object itself, while deep copy will not only copy the object, but also recursively copy the object associated with the object.

Deep copy may encounter two problems:

• If an object directly or indirectly references itself, it will lead to endless recursive copies;

• Deep copy may also copy data originally designed to be shared by multiple objects.

Solution: deepcopy can save the copied objects through the memo dictionary, so as to avoid the problem of self reference recursion
Note: the slicing operation [:] of the list is equivalent to the shallow copy of the list object

• copy:

- when the outermost object is of variable type, the object obtained after copy points to the new memory space; when the outermost object is of immutable type, the object obtained after copy points to the memory space of the original object (Note: whether the outermost layer of the shallow copy object is of variable type)

• Deep copy: copies other objects referenced in the object in addition to the object itself

- as long as one of the copied contents is a variable type, deepcopy must be a deep copy

```>>> a = [1, 2, 3]
>>> b = list(a)
>>> print(id(a), id(b))
# a and b have different identities
140601785066200 140601784764968
>>> for x, y in zip(a, b):       # But they contain child objects with the same identity
print(id(x), id(y))
...
140601911441984 140601911441984
140601911442016 140601911442016
140601911442048 140601911442048
```

Note: there is only one way of deep copy: the deepcopy function in the copy module.

1. Assignment: simply copy the reference of the object. The IDs of the two objects are the same.

2. Shallow copy: creates a new composite object that shares child objects in memory with the original object.

3. Deep copy: create a new composite object and copy all sub objects recursively. The new composite object has no association with the original object. Although immutable sub objects are actually shared, their mutual independence is not affected.

### Dict (Dictionary) operation

#### dict.clear()

clear() clears all the contents of the dictionary

```dic = {'clear': 'clear',}
dic.clear()
dic
output: {}

```

#### dict.fromkeys()

fromkeys() creates a new dictionary. The element in the sequence iterable is used as the key of the dictionary. Value is the initial value corresponding to all the keys of the dictionary

• iterable: iteratable object, the key of the new dictionary

• Value: optional parameter. Set the value corresponding to the key sequence. The default value is None

```dict.fromkeys(['key1', 'key2'],'Python')
output: {'key1': 'Python', 'key2': 'Python'}

```

#### dict.get()

get(key, default=None) searches according to the specified key value. If the key is in the dictionary, the value of the key is returned; otherwise, it is None

```dic = {'get_value': 'demo01'}
dic.get('get_value')
output:'demo01'
```

#### dict.items()

items() returns the view object, which is a key/value pair that can be traversed. You can use list() to convert it into a list

```dic = {'key01': 'value01',
'key02': 'value02'}
list(dic.items())
output:[('key01','value01'),('key02','value02')]
```

#### dict.keys()

keys() returns a view object whose value is the key of the dictionary, which can be converted into a list

```dic = {'key01': 'value01',
'key02': 'value02'}
dic.keys()
output:dict_keys(['key01',key02'])
```

#### dict.setdefault()

setdefault(key, default=None) if the key is not in the dictionary, insert the key with the value of None. Returns the value of the key if the key is in the dictionary

```dic = {'key01': 'value01',
'key02': 'value02'}
dic.setdefault('key02','value03)
output:'value02'

dic = {'key01': 'value01',
'key02': 'value02'}
dic.setdefault('key03','value03)
dic
output:{'key01': 'value01',
'key02': 'value02'
'key03':'value03'}

```

#### dict.update()

dict.update(dict1) updates the key/value pair of dict1 in the dictionary to dict. When the key of dict1 appears in dict, modify the value in dict. If the key does not appear in dict, add this pair of key/value

```dic1 = {'key01': 'value01',
'key02': 'value02'}
dic2 = {'key01': 'value01',
'key02': 'value02'}
dic1.update(dict2)
dic1
output:{'key01': 'value01',
'key02': 'value02',
'key01': 'value01',
'key02': 'value02'}
```

#### dict.values()

values() returns a view object with the value of the dictionary, which can be converted into a list

```dic = {'key01': 'value01',
'key02': 'value02'}
dic.values()
output:dict_values(['value01', 'value02'])
```

#### dict.pop() & dict.popitem()

dict.pop() deletes the key/value of the specified key. If the key is not found, an error is reported

popitem() deletes the last element in the dictionary and returns a tuple (key, value) pair. If the dictionary is empty, an error is reported

```dic = {'key01': 'value01',
'key02': 'value02'}
dic.pop('key01')
dic
output:{'key02':'value02'}

dic = {'key01': 'value01',
'key02': 'value02'}
dic.popitem()
output:{'key02':'value02'}
```

### set

Adds an element to the collection, but has no effect if the element already appears in the collection

Note: if the element of add is already in the collection, the collection will not change

```set1 = {'set01','set02','set03'}
set1
output:{'set01','set02','set03','python'}
```

#### set.clear()

clear() removes all elements from the collection

```set1 = {'python'}
set1.clear()
set1
output: set()

```

#### set.difference() & set.difference_update()

difference() returns the difference set of multiple sets. Generally speaking, it returns which elements in the first set do not appear in other sets

difference_ The difference between the update () method and the difference() method is that the difference() method returns a new collection with the same element removed, while the difference() method_ The update () method directly removes the elements in the original collection and has no return value

```set1 = {'set01',
'c++',
'python'}
set2 = {'python', 'c++'}
set3 = {'Python'}
set1.difference(set2, set3)
output: {'set01'}

set1 = {'set01',
'c++',
'python'}
set2 = {'python', 'c++'}
set3 = {'Python'}
set1.difference_update(set2, set3)
set1
output: set()
```

discard() deletes the specified element in the collection. If the element specified for removal is not in the collection, it is not removed

```set1 = {'set01','set02','set03'}
output:{'set02','set03'}
```

#### set.intersection() & set.intersection_update()

• intersection() returns the intersection of sets. If there is no intersection, an empty set() is returned

• intersection_ The difference between the update () method and the intersection() method is that the intersection() method returns the intersection of the set as a new set, while the intersection_ The update () method directly modifies the elements in the original set, leaving only the intersection elements and no return value.

```set1 = {'set01','set02','set03'}
set2 = {'set01', 'c++'}
set03 = {'set01'}
set1.intersection(set2, set3)
output:{'set01'}

set1 = {'set01','set02','set03'}
set2 = {'set01', 'c++'}
set03 = {'set01'}
set1.intersection_update(set2, set3)
set1
output:{'set01'}

```

#### set.isdisjoint()

isdisjoint() determines whether two collections contain the same elements. If yes, it returns False, and if no, it returns True

```set1 = {'set01','set02','set03'}
set2 = {'set01','set02'}
set1.isdisjoint(set2)
output:False
```

#### set.issubset()&set.issuperset()

• issubset(set1) determines whether set set2 is a subset of set1. True if yes, False otherwise

• issuperset(set2) determines whether set2 is a subset of set1. True if yes, False otherwise. It is used in the same way as issubset(), except that the position of the parameter is opposite

```set1 = {'set01','set02','set03'}
set2 = {'set01','set02'}
set2.issubset(set1)
output:True

set1 = {'set01','set02','set03'}
set2 = {'set01','set02'}
set1.issuperset(set2)
output:True
```

#### set1.pop()&set.remove()

• pop() removes and returns any element in the collection. If the set is empty, an error is reported

• remove() removes the specified element from the collection. If the element is not in the collection, an error occurs

```set1 = {'set01','set02','set03'}
set1.pop()
output:'set03'
set1.remove('set01')
set1
output:{'set02'}

```

#### set.symmetric_difference()&set.symmetric_difference_update()

• symmetric_difference() returns the set of elements that are not repeated in the two sets, that is, the complement of the two sets, which is the same as ^

• symmetric_difference_update(set2) removes the same elements in set1 as in set2 and inserts different elements in set2 set into set1. Simply put, it is to assign the complement of set1 and set2 to set1

```set1 = {'set01','set02','set03'}
set2 = {'set01','set02'}
set1.symmetric_difference(set2)  ==> set1 ^ set2
output:{'set03'}

set1 = {'set01','set02','set03'}
set2 = {'set01','set02'}
set1.symmetric_difference_update(set2) ==>set1 = set1 ^ set2
set1
output:{'set03'}

```

#### set.union()

union() returns the union of multiple sets. The same function as 𞓜

```set1 = {'set01','set02','set03'}
set2 = {'set01','set02','set04'}
set3 = {'set01','set02','set05'}
set1.union(set2, set3)
output:{'set01','set02','set03','set04','set05'}

```

#### set.update()

update() updates the collection using itself and other unions

```set1 = {'set01','set02','set03'}
set1.update([1,2,3])
output:{'set01','set02','set03',1,2,3}
```

Tags: Python Back-end

Posted on Mon, 25 Oct 2021 08:37:24 -0400 by hexguy