Home > Article > Backend Development > Summary of the six commonly used data types in Python
This article brings you a summary of the six commonly used data types in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
When you first start learning a programming language, in addition to understanding the operating environment and language type, the most basic thing is to start learning the basic data types of the language.
Python’s six commonly used data types:
int integer
float floating point number
str String
list List
tuple Tuple
dict Dictionary
To explain these, let’s first talk about variables and variable names in python.
A variable is essentially a memory with a special format, and the variable name is an alias pointing to this memory.
Variables in python do not need to be declared, all variables must be assigned a value before they can be used.
Steps of assignment:
a = 100
Step one: Prepare the value 100
Part two: Prepare the variable name a
Part three: Associate the value with the name
1. Integers
Python merges int and long in some other static languages, that is, integer and long integer into one.
Int in python is side-length, which means that it can store infinitely large integers, but this is unrealistic because
there is not so much memory to allocate.
Integer type not only supports decimal, but also binary, octal, and hexadecimal.
can be converted to each other in the following way:
print(bin(20)) #转换二进制 print(oct(20)) #转换八进制 print(hex(20)) #转换十六进制
2. Floating point type
Floating point numbers are decimals, such as 22.1, 44.2, and scientific notation can also be used, such as: 1.22e8.
Python supports four mixed arithmetic operations directly on integers and floating point numbers.
The result of integer operations is still an integer, and the result of a floating-point operation is still a floating-point number, but the result of a mixed operation of integers and floating-point numbers becomes a floating-point number.
a = 1 b = 1.1 print(type(a+b)) #<class 'float'>
3. String
String is the most commonly used data type in any programming language.
Creating a string is very simple, it is also the three steps mentioned above, but you need to add single quotes or double quotes.
a = "hello python"
You can also use """ to create a multi-line string:
a = """ hello python """
Strings can be intercepted or connected in the following ways:
print (str[0:4]) 输出第一个到倒数第四个的所有字符 print (str[0]) 输出单字符 第1个字符 print (str[3:]) 输出从第四个开始之后的所有字符 print (str * 2) 输出字符串两次 print (str + "bbbb") 连接字符串
Common functions for strings:
str.strip() Eliminate the blank characters on the left and right sides of the string s (including 't', 'n', 'r', '')
len(str) Get the length of the string
str.upper () Convert to uppercase
str.lower() Convert to lowercase
str.title() Capitalize the first letter of each word
str.capitalize() Capitalize the first letter
String flip:
a = 'abcde' print(a[::-1])
String splitting:
a = 'hello,python' print(a.split(',')) #['hello', 'python'] 返回一个列表
Correspondingly, there is a way to connect list elements into strings:
a = ['hello', 'python'] str = '-' print(str.join(a)) # hello-python
4. List
The way to write a list is a square bracket The values within are separated by commas. For example, ['hello', 'python'] above.
The data items of the list do not need to be of the same type. Each element in the list is assigned a numeric index, the first index is 0, the second index is 1, and so on.
Accessing the values in the list can be done in the following ways:
list1 = [1, 2, 3, 4, 5, 6] print(list1[2])
print ("list1[2:5]: ", list1[2:5])
Common operations on lists :
list1.append('7') Appends an element at the end, only one can be added at a time
len(list1) Returns the number of list elements
max(list1) Returns the maximum value of list elements
min(list1) Returns the minimum value of a list element
list1.count(obj) Counts the number of times an element appears in the list
list1.index(obj) Finds the first match of a certain value from the list The index position of the item
list1.reverse() Reverse the element in the list
list1.clear() Clear the list
list1.extend(seq) Append multiple values from another sequence at the end of the list at one time , that is, the list is expanded.
The difference between append and extend:
A = ['a', 'b', 'c'] A.append(['d', 'e']) print(A) # ['a', 'b', 'c', ['d', 'e']] B = ['a', 'b', 'c'] B.extend(['d', 'e']) print(B) # ['a', 'b', 'c', 'd', 'e']
The extend method can only receive the list type. It adds each element in this list to the original list.
append It can receive any type and append it to the end of the original list.
5. Tuple
The creation of tuple is also very simple, similar to list, except that '[]' is replaced with '()' .
tup1 = ('hello', 'python')
When there is only one element in the tuple, please note:
tup2 = (10) tup3 = ('a') print(type(tup2)) #<class 'int'> print(type(tup3)) #<class 'str'>
Because this will be regarded as an operator by the interpreter, the correct method is to add a comma after the first element.
tup4 = ('a',) print(type(tup4)) #<class 'tuple'>
Tuples can also use subscript indexes to access the values in the tuple:
tup5 = ('hello', 'python', 'hello', 'word') print(tup5[1]) #python print(tup5[1:3]) #('python', 'hello')
Note:
Tuples cannot be modified.
tup6 = ('hello', 'python', 'hello', 'word') tup6[2] = 'aaa'
An exception will appear above: TypeError: 'tuple' object does not support item assignment
But if the tuple contains a list, then this list can be modified.
tup7 = ('hello', 'python', 'hello', 'word', ['aa', 'bb', 'cc']) tup7[-1][1] = 'ddd' print(tup7) # ('hello', 'python', 'hello', 'word', ['aa', 'ddd', 'cc'])
Tuple operator:
len(tup) Calculate the number of elements
tup1 tup2 Connect to generate a new tuple
tup * 4 Tuple copy
num in tup Whether the element is Exists, returns True/False
六、字典
python中的字典就是key,value的形式。使用大括号包含起来。字典中的成员的键是唯一的,如果出现多个同名的键,那么写在后面覆盖前面的值。
形式如下:
dict1 = {'a' : 1, 'b' : 2}
字典的常用操作最基本的也就是增删改查:
获取:
直接通过键来获取。
dict['b'] # 2
dict.keys() 获取字典中所有的键
dict.values()获取字典中的所有的值
增加:
dict1['c'] = 3 #{'a': 1, 'b': 2, 'c': 3} #如果键存在则更新对应的值
修改:
直接给键进行再次赋值就可以修改键对应的值了。
如果键不存在,则变成添加成员。
还可以通过:
dict1.update({"a":"11"}) dict1.setdefault("a", "222") # 已存在的键则修改无效 dict1.setdefault("d","222") # 不存在的话则创建 dict1.setdefault("e") # 没有设置值为None
删除:
使用pop删除指定键对应的成员,同时返回该值
print(dict1) # {'a': '11', 'b': 2, 'c': 3, 'd': '222', 'e': None} print(dict1.pop("a")) # a print(dict1) # {'b': 2, 'c': 3, 'd': '222', 'e': None} #在不设置默认值的情况下,使用pop删除不存在的键,会报错。 print(dict1.pop("f")) # 报错 KeyError: 'f'
如果设置了默认值, print(dict1.pop("f", None)),则不会报错,返回这个默认值。
判断是否删除成功可以通过下面方式来判断:
if dict1.pop("f", None) == None: print('键不存在') else: print('删除成功')
以上则是python中最基本的数据类型以及用法,当然还有其他的数据类型,暂时只列举了这些。
The above is the detailed content of Summary of the six commonly used data types in Python. For more information, please follow other related articles on the PHP Chinese website!