1. Data type classification
Common data types in Python3 are:
- Number (number)
- String (String)
- bool (boolean type)
- List (list)
- Tuple (tuple)
- Set (set)
- Dictionary (Dictionary)
Among the six standard data types in Python3:
Immutable data (3):Number (number), String (string), Tuple (tuple);
Variable data (3):List (list), Dictionary (dictionary), Set (set).
-
Basic
- Number (number)
- String (String)
-
Multi-field
- List (list)
- Tuple (tuple)
- Dictionary (Dictionary)
- Set (set)
# Listmy_list = [0, 1, 2, 3, 4, 5, 6, 7, 8] # Tuple (value cannot be modified)my_tuple = (1, 2, 3, 4) # Dictionarymy_info = {'name': 'Zhang San', 'age': 18, 'address': 'Beijing'} # Set (set)set01 = {1, 2, 3, 4}
2. Basic data types
1. Number (number)
- Python3 Supportint, float, bool, complex (plural)。
- In Python 3, there is only one integer type int, which is represented as a long integer, and there is no Long in python2.
- Like most languages, the assignment and calculation of numeric types are very intuitive.
- Built-in
type()
Functions can be used to query the object type referred to by a variable. - Python can assign values to multiple variables at the same time, such as a, b = 1, 2.
- A variable can be assigned to objects of different types.
- The division of numeric values contains two operators:/Returns a floating point number,//Returns an integer.
- Python converts integers into floating point numbers when mixed calculations
>>> 5 + 4 # Addition9 >>> 4.3 - 2 # Subtraction2.3 >>> 3 * 7 # Multiplication21 >>> 2 / 4 # Division to get a floating point number0.5 >>> 2 // 4 # Division to get an integer0 >>> 17 % 3 # Get the rest2 >>> 2 ** 5 #32
2. String (String)
- Backslashes can be used for escape, and r can prevent backslashes from being escaped.
- Strings can be concatenated together with the + operator and repeated with the * operator.
- There are two indexing methods for strings in Python, starting from left to right with 0 and starting from right to left with -1.
- Strings in Python cannot be changed.
print(str[0:-1]) # Print the first to the penultimate character of the string (not including the penultimate character)print(str[0]) # Print the first character of the stringprint(str[2:5]) # Print the third to fifth characters of the string (including the fifth character)print(str[2:]) # Print string starting from the third character to the end str_01 = 'my name is:{}, age:{}' print(str_01.format('Zhang San', 18)) str_02 = 'my name is:{name}, age:{age}' print(str_02.format(name='Zhang San', age=18)) str_03 = 'my name is:{name}, age:{age}' print(str_03.format_map({'name': 'Zhang San', 'age': 18}))
Python uses backslashes\
Escape special characters. If you don't want the backslash to escape, you can add one in front of the string.r
, representing the original string:
print('Ru\noob') Ru oob print(r'Ru\noob') Ru\noob
encode()
、decode()
method
-
encode()
Method encodes the string in the specified encoding format. The errors parameter can specify different error handling schemes. -
decode()
Method decodes the bytes object in the specified encoding format. The default encoding is ‘utf-8’. - This method returns the encoded string, which is a bytes object.
(encoding='UTF-8',errors='strict') (encoding="utf-8", errors="strict")
- encoding – The encoding to use, such as: UTF-8.
- errors – Set different error handling schemes. The default is ‘strict’, meaning that an encoding error causes a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any values registered via codecs.register_error().
#!/usr/bin/python3 str = "" str_utf8 = ("UTF-8", 'strict') str_gbk = ("GBK") print("UTF-8 Encoding:", str_utf8) print("GBK encoding:", str_gbk) print("UTF-8 Decoding:", str_utf8.decode('UTF-8')) print("GBK decoding:", str_gbk.decode('GBK', 'strict'))
result:
UTF-8 coding: b'\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b' GBK coding: b'\xb2\xcb\xc4\xf1\xbd\xcc\xb3\xcc' UTF-8 decoding: GBK decoding:
3.2 format format string
# 1、 print('{}Website: "{}!"'.format('', '')) # 2、 print('{name}Website: {site}'.format(name='', site='')) # 3、 print('{0} and {1}'.format('Google', 'Runoob')) # Can be combined anywayprint('Site List {0}, {1}, and {other}。'.format('Google', 'Runoob', other='Taobao')) # 4、 table = {'Google': 1, 'Runoob': 2, 'Taobao': 3} print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
3. Bool (Bool type)
The boolean type is True or False.
In Python, both True and False are keywords that represent boolean values.
Boolean types can be used to control the process of a program, such as determining whether a certain condition is true, or executing a certain piece of code when a certain condition is satisfied.
Boolean type features:
- There are only two values for Boolean types: True and False.
- Boolean types can be compared with other data types, such as numbers, strings, etc. When comparing, Python treats True as 1 and False as 0.
- Boolean types can be used with logical operators, including and, or, and not. These operators can be used to combine multiple Boolean expressions to generate a new Boolean value.
- Boolean types can also be converted to other data types, such as integers, floating-point numbers, and strings. During conversion, True will be converted to 1 and False will be converted to 0.
a = True b = False # Comparison operatorprint(2 < 3) # True print(2 == 3) # False # Logical operatorsprint(a and b) # False print(a or b) # True print(not a) # False # Type conversionprint(int(a)) # 1 print(float(b)) # 0.0 print(str(a)) # "True"
In Python3,bool
yesint
Subclass ofTrue
andFalse
Can be added to the numbers,True==1、False==0
Will returnTrue
, but can be passedis
To determine the type.
a1 = True print(type(a1)) print(a1 + 100) <class 'bool'> 101
4、Bytes
Convert string toBytes
# parse to bytes: b'Hello,World'print('Hello,World'.encode())
Bytes
Convert to string
# Create a bytes objectbytes_data = b'Hello, World!' # b'Hello, World!' print(bytes_data) # Convert the bytes object to a stringstring_data = bytes_data.decode('utf-8') print(string_data)
3. Multi-value storage
1. List (list)
Add, delete, modify, check:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8] #1. Addmy_list.append('333') # Add another collection to the listinsert_list = [1, 23] my_list.extend(insert_list) # Insert element before specifying positionmy_list.insert(2, '34') # 2. Deletemy_list.remove() # 3. Changemy_list[1] = 'Zhang San' #4. Check# Check whether it exists in the collectionprint('Zhang San' in my_list) # Query the indexmy_list.index('Zhang San') my_list.index('Zhang San', 1, 4) # Query quantitymy_list.count('Zhang San')
other
# Loopfor one in my_list: # print(one) print(one, end='==') print(one, end='==\n%%% ') # Sort# Sort - positive ordermy_list.sort() # Sort - Reversemy_list.sort(reverse=True)
Function built-in methods
method | Serial number |
---|---|
(obj) |
Add new object at the end of the list |
(obj) |
Count the number of times an element appears in the list |
(seq) |
Append multiple values from another sequence at one time at the end of the list (extend the original list with the new list) |
(obj) |
Find the index position of the first match of a value from the list |
(index, obj) |
Insert objects into list |
([index=-1\]) |
Removes an element in the list (the last element by default) and returns the value of that element |
(obj) |
Remove the first match of a value in the list |
() |
Reverse list elements |
( key=None, reverse=False) |
Sort the original list |
() |
Clear the list |
() |
Copy the list |
2. Tuple (tuple)
Python's tuples are similar to lists, the difference is that the elements of the tuple cannot be modified.
# tuple tuplemy_tuple = (1, 2, 3, 4) # Check - a certain valueprint(my_tuple[1]) # Check—Query the index position where the query is located (front closed right opening interval) (start index: 0)print(my_tuple.index(2, 1, 3)) # Check - the number of certain valuesprint(my_tuple.count(1))
Python tuples contain the following built-in functions
function | Methods and descriptions | Example |
---|---|---|
len(tuple) |
Calculate the number of tuple elements | >>> tuple1 = ('Google', 'Runoob', 'Taobao') |
max(tuple) |
Returns the maximum value of an element in a tuple | max(tuple2) |
min(tuple) |
Returns the minimum value of the element in the tuple | min(tuple2) |
tuple(iterable) |
Convert an iterable series to a tuple | tuple1=tuple(['Google', 'Taobao', 'Runoob', 'Baidu']) |
3. Dictionary (Dictionary)
Add, delete, modify and check
my_info = {'name': 'Zhang San', 'age': 18, 'address': 'Beijing'} # 1. Query elements# Check - Query a single (valueless exception)print(my_info['name']) print(my_info['age']) # Check - Query single (return None without value)print(my_info.get('name1')) # Check - Query single (return specified value without value)print(my_info.get('name2', 'Li Si')) # 2. Modify elementsmy_info['name'] = 'Wang Wu' #3. Add elements# Add element - if the key does not exist, add itmy_info['id'] = 1234 #4. Delete elements# Delete an element - delete a single elementdel my_info['id'] # Delete-delete dictionary (the query will report an errordel my_info # Delete—Clear field (value {})my_info.clear()
Other APIs
#5. Other APIs# Measure the number of key-value pairs in the dictionaryprint(len(my_info)) # Return a list containing all KEYs in the dictionaryprint(my_info.keys()) # Return a list containing all values of the dictionaryprint(my_info.values()) # Return a list of all (key, value) ancestorsprint(my_info.items())
method | Functions and descriptions |
---|---|
() |
Delete all elements in the dictionary |
() |
Return a shallow copy of a dictionary |
() |
Create a new dictionary, use elements in sequence seq as the keys of the dictionary, and val is the initial value corresponding to all keys of the dictionary |
(key, default=None) |
Returns the value of the specified key, if the key is not in the dictionary, return the default value set by default |
key in dict |
If the key returns true in the dictionary dict, otherwise return false |
() |
Return a view object as a list |
() |
Return a view object |
(key, default=None) |
Similar, but if the key does not exist in the dictionary, the key will be added and the value will be set to default |
(dict2) |
Update the key/value pairs of dictionary dict2 to dict |
() |
Return a view object |
pop(key[,default\]) |
Delete the value corresponding to the dictionary key (key) and return the deleted value. |
popitem() |
Return and delete the last pair of keys and values in the dictionary. |
4. Set (set)
- A set is an unordered sequence of non-repetitive elements.
- Elements in a collection will not be repeated, and common set operations such as intersection, union, and difference can be performed.
- Braces can be used{ }Create a collection, use commas between elements,Separate, or can also be usedset()Function creates a collection.
# 0. Create a collectionset01 = {1, 2, 3, 4} # Create a collection directly using bracesset02 = set([4, 5, 6, 7]) # Create a collection from a list using the set() function #1. Add# 1-1 Add element x to the collection s, and do nothing if the element already exists.(100) # 1-2 Add elements, and the parameters can be lists, tuples, dictionaries, etc.([1, 2, ]) # 2. Delete# 2-1 Remove element x from collection s, an error occurs if the element does not exist(1) # 2-2 Remove elements from the collection and if the element does not exist, no error will occur(1) # 2-3 Randomly delete an element in the collection() # 3. Others# Determine whether the element is in the set (False)print('1' in set03) # Calculate the number of set elementsprint(len(set01)) # Clear the collection()
Complete list of built-in methods for collections
method | describe |
---|---|
add() | Add elements to the collection |
clear() | Remove all elements from the collection |
copy() | Copy a collection |
difference() | Returns the difference set of multiple sets |
difference_update() | Removes an element in the collection, which also exists in the specified collection. |
discard() | Delete the specified element in the collection |
intersection() | Return the intersection of the set |
intersection_update() | Returns the intersection of the set. |
isdisjoint() | Determines whether the two sets contain the same element, if True is not returned, otherwise False is returned. |
issubset() | Determines whether the specified set is a subset of the method parameter set. |
issuperset() | Determine whether the parameter set of this method is a subset of the specified set |
pop() | Randomly remove elements |
remove() | Remove the specified element |
symmetric_difference() | Returns a collection of elements that are not repeated in two sets. |
symmetric_difference_update() | Removes the same element in the current set in another specified set, and inserts different elements in the other specified set into the current set. |
union() | Returns the union of two sets |
update() | Add elements to the collection |
len() | Calculate the number of set elements |
4. Others
1、Json
method | effect | Return type |
---|---|---|
eval(string expression) | The eval() function is used to execute a [string expression] and return the value of the expression. | list、dict、tuple |
() | Encoding python objects into Json strings | Returns the json string |
() | Decode Json string into python object | Return python object |
() | Convert objects in python into json and store them in a file | No return |
() | Convert the json format in the file into a python object to extract it | Return python object |
V. Other functions
1、print()
print(*objects, sep=' ', end='\n', file=, flush=False)
-
objects
: Plural, indicating that multiple objects can be output at once. When outputting multiple objects, it needs to be separated by ,. -
sep
: Used to space multiple objects, the default value is a space. -
end
: Used to set the ending. The default value is line break \n, which we can change to other strings. -
file
: The file object to be written. -
flush
: Whether the output is cached is usually determined by file, but if the flush keyword parameter is True, the stream will be forced to refresh.
# 1 2 3 4 5 print('1', '2', '3', '4', '5') # 1+2+3 print('1', '2', '3', sep='+') # 1++2++3== print('1', '2', '3', sep='++', end='==')
Summarize
This is the end of this article about the processing of common Python data types. For more related Python data types, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!