Home >Backend Development >Python Tutorial >What are the data types in python
There are 9 data types in python, namely 1, string 2, Boolean type 3, integer 4, floating point number 5, number 6, list 7, tuple 8, dictionary 9, and date.
1. String
1.1. How to use strings in Python
a. Use single Quotation marks (')
Use single quotation marks to express a string, for example:
str='this is string'; print str;
b, use double quotation marks (")
The string in double quotation marks is the same as the single quotation mark The usage of strings in quotation marks is exactly the same, for example:
str="this is string";
print str;
c, use triple quotation marks (''')
Use triple quotes to represent multi-line strings. You can freely use single quotes and double quotes within the triple quotes, for example:
str='''this is string this is pythod string this is string''' print str;
2, Boolean type
bool=False; print bool; bool=True; print bool;
3, integer
int=20; print int;
4, floating point number
float=2.3; print float;
5, number
Includes integers and floating point numbers.
5.1. Delete numerical object references, for example:
a=1; b=2; c=3; del a; del b, c; #print a; #删除a变量后,再调用a变量会报错
5.2. Numeric type conversion
int(x [,base]) 将x转换为一个整数 float(x ) 将x转换到一个浮点数 complex(real [,imag]) 创建一个复数 str(x) 将对象x转换为字符串 repr(x) 将对象x转换为表达式字符串 eval(str) 用来计算在字符串中的有效Python表达式,并返回一个对象 tuple(s) 将序列s转换为一个元组 list(s) 将序列s转换为一个列表 chr(x) 将一个整数转换为一个字符 unichr(x) 将一个整数转换为Unicode字符 ord(x) 将一个字符转换为它的整数值 hex(x) 将一个整数转换为一个十六进制字符串 oct(x) 将一个整数转换为一个八进制字符串
5.3. Mathematical function
abs(x) 返回数字的绝对值,如abs(-10) 返回 10 ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5 cmp(x, y) 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1 exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0 floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4 log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0 max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。 min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。 modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。 pow(x, y) x**y 运算后的值。 round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。 sqrt(x) 返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回 2+0j
6. List
6.1. Initialization list, for example:
list=['physics', 'chemistry', 1997, 2000]; nums=[1, 3, 5, 7, 8, 13, 20];
6.2. Access the values in the list, for example:
'''nums[0]: 1''' print "nums[0]:", nums[0] '''nums[2:5]: [5, 7, 8] 从下标为2的元素切割到下标为5的元素,但不包含下标为5的元素''' print "nums[2:5]:", nums[2:5] '''nums[1:]: [3, 5, 7, 8, 13, 20] 从下标为1切割到最后一个元素''' print "nums[1:]:", nums[1:] '''nums[:-3]: [1, 3, 5, 7] 从最开始的元素一直切割到倒数第3个元素,但不包含倒数第三个元素''' print "nums[:-3]:", nums[:-3] '''nums[:]: [1, 3, 5, 7, 8, 13, 20] 返回所有元素''' print "nums[:]:", nums[:]
6.3. Update the list, for example:
nums[0]="ljq"; print nums[0];
6.4. Delete list elements
del nums[0]; '''nums[:]: [3, 5, 7, 8, 13, 20]''' print "nums[:]:", nums[:];
6.5. List script The operators
list pairs and * are similar to string operators. The symbol is used to combine lists, and the * symbol is used to repeat lists, for example:
print len([1, 2, 3]); #3 print [1, 2, 3] + [4, 5, 6]; #[1, 2, 3, 4, 5, 6] print ['Hi!'] * 4; #['Hi!', 'Hi!', 'Hi!', 'Hi!'] print 3 in [1, 2, 3] #True for x in [1, 2, 3]: print x, #1 2 3
6.6, List interception
L=['spam', 'Spam', 'SPAM!']; print L[2]; #'SPAM!' print L[-2]; #'Spam' print L[1:]; #['Spam', 'SPAM!']
6.7, List functions & methods
list.append(obj) 在列表末尾添加新的对象 list.count(obj) 统计某个元素在列表中出现的次数 list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) list.index(obj) 从列表中找出某个值第一个匹配项的索引位置,索引从0开始 list.insert(index, obj) 将对象插入列表 list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 list.remove(obj) 移除列表中某个值的第一个匹配项 list.reverse() 反向列表中元素,倒转 list.sort([func]) 对原列表进行排序
7, Tuple(tuple)
Python’s tuple is similar to the list, the difference lies in the Elements cannot be modified; use parentheses () for tuples and square brackets [] for lists; tuple creation is very simple, just add elements in the brackets and separate them with commas (,), for example:
tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d";
Create an empty tuple, for example: tup = ();
When there is only one element in the tuple, you need to add a comma after the element, for example: tup1 = (50,) ;
Tuples are similar to strings. The subscript index starts from 0 and can be intercepted, combined, etc.
7.1. Access tuples
tup1 = ('physics', 'chemistry', 1997, 2000); #tup1[0]: physics print "tup1[0]: ", tup1[0] #tup1[1:5]: ('chemistry', 1997) print "tup1[1:5]: ", tup1[1:3]
7.2. Modify tuples The element values in the group
are not allowed to be modified, but we can connect and combine the tuples, for example:
tup1 = (12, 34.56); tup2 = ('abc', 'xyz'); # 以下修改元组元素操作是非法的。 # tup1[0] = 100; # 创建一个新的元组 tup3 = tup1 + tup2; print tup3; #(12, 34.56, 'abc', 'xyz')
7.3, delete the tuple
The element values in the group are not allowed to be deleted. You can use the del statement to delete the entire tuple, for example:
tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup;
7.4. Tuple operator
is the same as string. You can use the sign and * sign to perform operations. This means that they can be combined and copied, resulting in a new tuple.
7.5, Tuple index & interception
L = ('spam', 'Spam', 'SPAM!'); print L[2]; #'SPAM!' print L[-2]; #'Spam' print L[1:]; #['Spam', 'SPAM!']
7.6, Tuple built-in function
cmp(tuple1, tuple2) 比较两个元组元素。 len(tuple) 计算元组元素个数。 max(tuple) 返回元组中元素最大值。 min(tuple) 返回元组中元素最小值。 tuple(seq) 将列表转换为元组。
8, Dictionary
8.1, Introduction to Dictionary
Dictionary (dictionary) is the most flexible built-in data structure type in Python besides lists. A list is an ordered combination of objects, and a dictionary is an unordered collection of objects. The difference between the two is that the elements in the dictionary are accessed by key, not by offset.
The dictionary consists of keys and corresponding values. Dictionaries are also called associative arrays or hash tables. The basic syntax is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'};
You can also create a dictionary like this:
dict1 = { 'abc': 456 }; dict2 = { 'abc': 123, 98.6: 37 };
Each key and value must be separated by a colon (:), each pair is separated by a comma, and the whole is placed in curly braces ({}). Keys must be unique, but values do not; values can be of any data type, but must be immutable, such as strings, numbers, or tuples.
8.2. Access the values in the dictionary
#!/usr/bin/python dict = {'name': 'Zara', 'age': 7, 'class': 'First'}; print "dict['name']: ", dict['name']; print "dict['age']: ", dict['age'];
8.3. Modify the dictionary
The method to add new content to the dictionary is to add new key/value pairs, modify or delete existing There are key/value pairs as follows:
#!/usr/bin/python dict = {'name': 'Zara', 'age': 7, 'class': 'First'}; dict["age"]=27; #修改已有键的值 dict["school"]="wutong"; #增加新的键/值对 print "dict['age']: ", dict['age']; print "dict['school']: ", dict['school'];
8.4. Delete dictionary
del dict['name']; # 删除键是'name'的条目 dict.clear(); # 清空词典所有条目 del dict ; # 删除词典
For example:
#!/usr/bin/python dict = {'name': 'Zara', 'age': 7, 'class': 'First'}; del dict['name']; #dict {'age': 7, 'class': 'First'} print "dict", dict;
Note: The dictionary does not exist, del will raise an exception
8.5. Dictionary built-in functions & methods
cmp(dict1, dict2) 比较两个字典元素。 len(dict) 计算字典元素个数,即键的总数。 str(dict) 输出字典可打印的字符串表示。 type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 radiansdict.clear() 删除字典内所有元素 radiansdict.copy() 返回一个字典的浅复制 radiansdict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值 radiansdict.get(key, default=None) 返回指定键的值,如果值不在字典中返回default值 radiansdict.has_key(key) 如果键在字典dict里返回true,否则返回false radiansdict.items() 以列表返回可遍历的(键, 值) 元组数组 radiansdict.keys() 以列表返回一个字典所有的键 radiansdict.setdefault(key, default=None) 和get()类似, 但如果键不已经存在于字典中,将会添加键并将值设为default radiansdict.update(dict2) 把字典dict2的键/值对更新到dict里 radiansdict.values() 以列表返回字典中的所有值
9. Date and time
9.1. Get the current time, for example:
import time, datetime; localtime = time.localtime(time.time()) #Local current time : time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0) print "Local current time :", localtime
Instructions: time.struct_time(tm_year=2014, tm_mon=3, tm_mday=21, tm_hour=15, tm_min=13, tm_sec=56, tm_wday=4, tm_yday=80, tm_isdst=0) belongs to the struct_time tuple. The struct_time tuple has the following Properties:
9.2. Get the formatted time
You can select various formats according to your needs, but the simplest function to get the readable time pattern is asctime():
2.1. Convert date to string
First choice: print time.strftime('%Y-%m-%d %H:%M:%S');
Secondly: print datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
Finally: print str(datetime.datetime.now ())[:19]
2.2. Convert string to date
expire_time = "2013-05-21 09:50:35" d = datetime.datetime.strptime(expire_time,"%Y-%m-%d %H:%M:%S") print d;
9.3. Get date difference
oneday = datetime.timedelta(days=1) #今天,2014-03-21 today = datetime.date.today() #昨天,2014-03-20 yesterday = datetime.date.today() - oneday #明天,2014-03-22 tomorrow = datetime.date.today() + oneday #获取今天零点的时间,2014-03-21 00:00:00 today_zero_time = datetime.datetime.strftime(today, '%Y-%m-%d %H:%M:%S') #0:00:00.001000 print datetime.timedelta(milliseconds=1), #1毫秒 #0:00:01 print datetime.timedelta(seconds=1), #1秒 #0:01:00 print datetime.timedelta(minutes=1), #1分钟 #1:00:00 print datetime.timedelta(hours=1), #1小时 #1 day, 0:00:00 print datetime.timedelta(days=1), #1天 #7 days, 0:00:00 print datetime.timedelta(weeks=1)
The above is the detailed content of What are the data types in python. For more information, please follow other related articles on the PHP Chinese website!