Python3 Basic Data Types
Category Programming Techniques
I. Explanation
In Python, variables do not need to be declared. Each variable must be assigned a value before it is used, and the variable is only created after it is assigned.
In Python, a variable is just a variable; it has no type. What we refer to as "type" is the type of the object in memory that the variable refers to.
The equal sign (=) is used to assign a value to a variable.
The left side of the equal sign (=) operator is a variable name, and the right side is the value stored in the variable.
For example:
#!/usr/bin/python3
counter = 100 # Integer variable
miles = 1000.0 # Floating-point variable
name = "tutorialpro" # String
a = b = c = 1 # Assigning values to multiple variables at once
a, b, c = 1, 2, 'hello' # Assigning multiple variables to multiple objects
II. Standard Data Types
Python3 has six standard data types:
Number (number)
String (string)
List (list)
Tuple (tuple)
Sets (set)
Dictionary (dictionary)
2.1 Number (Number)
Python3 supports int, float, bool, complex (complex number)
There is only one type of integer, int, which is represented as a long integer, without the Long of python2.
The built-in type() function can be used to query the type of the object referred to by a variable.
>>> a, b, c, d = 5, 6.7, true, 2+3j
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> a, b, c, d = 5, 6.7, True, 2+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
Note:
- Python can assign values to multiple variables at the same time, such as a, b = 1, 2.
- A variable can point to objects of different types through assignment.
- Division of numbers (/) always returns a floating-point number (print(2/4) outputs 0.5), use the // operator to get an integer.
- In mixed calculations, Python will convert integers into floating-point numbers.
- Boolean type: True and False, 1 and 0
- The del statement can delete defined objects, such as: del a, b
2.2 String (String)
Strings in Python are enclosed in single quotes (') or double quotes ("), and the backslash is used to escape special characters.
The syntax for string slicing is as follows:
variable[start_index:end_index]
The index value starts at 0, and -1 is the starting position from the end.
The plus sign (+) is the string concatenation operator, and the asterisk (*) indicates copying the current string, followed by the number of times to copy.
Example:
#!/usr/bin/python3
# -*- coding:UTF-8 -*-
str = 'hello,world!'
print(str) # Output the string
print(str[0:-1]) # Output all characters from the first to the second to last
print(str[0]) # Output the first character of the string
print(str[2:5]) # Output characters starting from the third to the fifth
print(str[2:]) # Output all characters after the third
print(str * 2) # Output the string twice
print(str + '你好') # Concatenate strings
print('------------------------------')
print('hello\nworld') # Use the backslash (\) + n to escape special characters
print(r'hello\nworld') # Add an r in front of the string to indicate a raw string, which does not escape
Execution result:
hello,world!
hello,world
h
llo
llo,world!
hello,world!hello,world!
hello,world!你好
------------------------------
hello
world
hello\nworld
Note:
- The backslash can be used to escape, and using r can prevent the backslash from escaping.
- Strings can be concatenated with the + operator and repeated with the * operator.
- Python has two indexing methods for
>>> dic = {'k1': 'v1', 'k2': 'v2'} >>> v = dic.get('k1') >>> print(v) v1
- Python has two indexing methods for
clear Clear
>>> dic = {'k1': 'v1', 'k2': 'v2'}
>>> v = dic.clear()
>>> print(dic)
{}
>>> print(v)
None
copy Copy (shallow copy)
>>> dic = {'k1': 'v1', 'k2': 'v2'}
>>> v = dic.copy()
>>> print(v)
{'k1': 'v1', 'k2': 'v2'}
pop Remove and get the corresponding value
>>> dic = {'k1': 'v1', 'k2': 'v2'}
>>> v = dic.pop('k1')
>>> print(dic)
{'k2': 'v2'}
>>> print(v)
v1
popitem Remove a random key-value pair and get the removed key-value
>>> dic = {'k1': 'v1', 'k2': 'v2'}
>>> v = dic.popitem()
>>> print(dic)
{'k1': 'v1'}
>>> print(v)
('k2', 'v2')
setdefault Add, do nothing if the key exists
>>> dic = {'k1': 'v1', 'k2': 'v2'}
>>> dic.setdefault('k3', 'v3')
>>> print(dic)
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
update Batch add or modify
dic = {'k1': 'v1', 'k2': 'v2'}
dic.update({'k3': 'v3', 'k4': 'v4'})
print(dic)
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3', 'k4': 'v4'}
Note:
- A dictionary is a mapping type, and its elements are key-value pairs.
- The keys in a dictionary must be immutable types and cannot be duplicated.
- Use { } to create an empty dictionary.
Three, Data Type Conversion
For data type conversion, you only need to use the data type as the function name.
The following built-in functions can perform conversions between data types. These functions return a new object representing the converted value.
Function | Description |
---|---|
int(x [,base]) | Convert x to an integer |
float(x) | Convert x to a floating point number |
complex(real [,imag]) | Create a complex number |
str(x) | Convert object x to a string |
repr(x) | Convert object x to an expression string |
eval(str) | Used to calculate a valid Python expression in a string and return an object |
tuple(s) | Convert sequence s to a tuple |
list(s) | Convert sequence s to a list |
set(s) | Convert to a mutable set |
dict(d) | Create a dictionary. d must be a sequence of (key,value) tuples. |
frozenset(s) | Convert to an immutable set |
chr(x) | Convert an integer to a character |
unichr(x) | Convert an integer to a Unicode character |
ord(x) | Convert a character to its integer value |
hex(x) | Convert an integer to a hexadecimal string |
oct(x) | Convert an integer to an octal string |
>
Original article link: https://segmentfault.com/a/1190000009722187