Home>Article>Backend Development> What are the python data types?
There are eight python data types, namely: numeric type (int and long), float type, complex type (complex), string type, list type, tuple type, dictionary type, Boolean type ( True and False).
Python data types have the following eight types
Number types
int and long
The reason why int and long should be put together is that after python3.x, int and long are no longer distinguished, and int is used uniformly. python2.x is still different. Let me take Python2.7 as an example:
>>> i = 10 >>> type(i)
>>> i=10000000000 >>> type(i)
So why 10 is int and 10000000000 is long. Of course, this is related to the maximum value of int. The maximum value of int type is 231-1, which is 2147483647 , you can also use sys.maxint.
>>> 2**31-1 2147483647L >>> sys.maxint 2147483647
Why is the value obtained using the above method a long type (adding 'L' after the number indicates a long type), because the value of 2**31 is 2147483648, which is a long type. Subtract 1 from a long type, and the result is still a long, but in fact the maximum value of the int type is 2147483647
>>> type(2147483647)>>> type(2147483648)
float type
float type and other languages Float is basically the same. Floating point numbers, to put it bluntly, are numbers with a decimal point. The accuracy is related to the machine. For example:
>>> i = 10000.1212 >>> type(i)
complex: plural type, you can check the relevant documents for the specific meaning and usage of.
String type
There are three ways to declare a string: single quotes, double quotes and triple quotes (including three single quotes or three double quotes). For example:
>>> str1 = 'hello world' >>> str2 = "hello world" >>> str3 = '''hello world''' >>> str4 = """hello world""" >>> print str1 hello world >>> print str2 hello world >>> print str3 hello world >>> print str4 hello world
Strings in Python have two data types: str type and unicode type. The str type uses ASCII encoding, which means it cannot represent Chinese.
The unicode type uses unicode encoding and can represent any characters, including Chinese and other languages.
And there is no char type in python like in c language, even a single character is a string type. The ASCII encoding used by the string by default. If you want to declare it as unicode type, you need to add 'u' or 'U' in front of the string. For example:
>>> str1 = "hello" >>> print str1 hello >>> str2 = u"中国" >>> print str2 中国
Since operations on strings often occur in projects, and there are many problems due to string encoding issues, let's talk about string encoding issues.
In the process of dealing with python, we often encounter three encodings: ASCII, Unicode and UTF-8. Please see this article for a detailed introduction.
My simple understanding is that ASCII encoding is suitable for English characters, Unicode is suitable for non-English characters (such as Chinese, Korean, etc.), and utf-8 is a storage and transmission format for Uncode characters. Re-encoding (encoded in 8-bit units). For example:
u = u'汉' print repr(u) # u'\u6c49' s = u.encode('UTF-8') print repr(s) # '\xe6\xb1\x89' u2 = s.decode('UTF-8') print repr(u2) # u'\u6c49' 解释:声明unicode字符串”汉“,它的unicode编码为”\u6c49“,经过utf-8编码转换后,它的编码变成”\xe6\xb1\x89“。
Summary of coding experience:
1. Declare the encoding format in the python file header;
#-*- coding: utf-8 -*-
2. Unify the strings Declared as unicode type, that is, add u or U before the string;
3. For file reading and writing operations, it is recommended to use codecs.open() instead of the built-in open(). Follow one principle, which one to use Write in one format, use which format to read;
Assume that there are several words "Chinese characters" in a text file saved in ANSI format. If you use the following code directly, and you want to read it on the GUI or in When printed in an IDE (for example, in sublime text, or in pydev), garbled characters or exceptions will appear, because codecs will read the content according to the encoding format of the text itself:
f = codecs.open("d:/test.txt") content = f.read() f.close() print content
Change Use the following method (only works for Chinese):
# -*- coding: utf-8 -*- import codecs f = codecs.open("d:/test.txt") content = f.read() f.close() if isinstance(content,unicode): print content.encode('utf-8') print "utf-8" else: print content.decode('gbk').encode('utf-8')
List type
The list is a modifiable collection type, and its elements can It can be basic types such as numbers and strings, or collection objects such as lists, tuples, and dictionaries, or even custom types. It is defined as follows:
>>> nums = [1,2,3,4] >>> type(nums)>>> print nums [1, 2, 3, 4] >>> strs = ["hello","world"] >>> print strs ['hello', 'world'] >>> lst = [1,"hello",False,nums,strs] >>> type(lst) >>> print lst [1, 'hello', False, [1, 2, 3, 4], ['hello', 'world']]
Use indexing to access list elements. The index starts from 0, supports negative indexes, and -1 is the last one.
>>> lst = [1,2,3,4,5] >>> print lst[0] >>> print lst[-1] >>> print lst[-2]
supports sharding operations and can access one Elements in the interval support different step sizes, and sharding can be used for data insertion and copy operations.
nums = [1,2,3,4,5] print nums[0:3] #[1, 2, 3] #前三个元素 print nums[3:] #[4, 5] #后两个元素 print nums[-3:] #[3, 4, 5] #后三个元素 不支持nums[-3:0] numsclone = nums[:] print numsclone #[1, 2, 3, 4, 5] 复制操作 print nums[0:4:2] #[1, 3] 步长为2 nums[3:3] = ["three","four"] #[1, 2, 3, 'three', 'four', 4, 5] 在3和4之间插入 nums[3:5] = [] #[1, 2, 3, 4, 5] 将第4和第5个元素替换为[] 即删除["three","four"] 支持加法和乘法操作 lst1 = ["hello","world"] lst2 = ['good','time'] print lst1+lst2 #['hello', 'world', 'good', 'time'] print lst1*5 #['hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world', 'hello', 'world']
Methods supported by the list, you can use the following method to view the public methods supported by the list:
>>> [x for x in dir([]) if not x.startswith("__")] ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] def compare(x,y): return 1 if x>y else -1 #【append】 在列表末尾插入元素 lst = [1,2,3,4,5] lst.append(6) print lst #[1, 2, 3, 4, 5, 6] lst.append("hello") print lst #[1, 2, 3, 4, 5, 6] #【pop】 删除一个元素,并返回此元素的值 支持索引 默认为最后一个 x = lst.pop() print x,lst #hello [1, 2, 3, 4, 5, 6] #默认删除最后一个元素 x = lst.pop(0) print x,lst #1 [2, 3, 4, 5, 6] 删除第一个元素 #【count】 返回一个元素出现的次数 print lst.count(2) #1 #【extend】 扩展列表 此方法与“+”操作的不同在于此方法改变原有列表,而“+”操作会产生一个新列表 lstextend = ["hello","world"] lst.extend(lstextend) print lst #[2, 3, 4, 5, 6, 'hello', 'world'] 在lst的基础上扩展了lstextend进来 #【index】 返回某个值第一次出现的索引位置,如果未找到会抛出异常 print lst.index("hello") #5 #print lst.index("kitty") #ValueError: 'kitty' is not in list 出现异常 #【remove】 移除列表中的某个元素,如果待移除的项不存在,会抛出异常 无返回值 lst.remove("hello") print lst #[2, 3, 4, 5, 6, 'world'] "hello" 被移除 #lst.remove("kitty") #ValueError: list.remove(x): x not in list #【reverse】 意为反转 没错 就是将列表元素倒序排列,无返回值 print lst #[2, 3, 4, 5, 6, 'world'] lst.reverse() print lst #[2, 3, 4, 5, 6, 'world'] #【sort】 排序 print lst #由于上面的反转 目前排序为 ['world', 6, 5, 4, 3, 2] lst.sort() print lst #排序后 [2, 3, 4, 5, 6, 'world'] nums = [10,5,4,2,3] print nums #[10,5,4,2,3] nums.sort(compare) print nums #[2, 3, 4, 5, 10]
Convert list to iterator.
The so-called iterator is an object with a next method (this method does not require any parameters when called). When the next method is called, the iterator returns its next value. If the next method is called but the iterator has no value to return, a StopIteration exception is raised. The advantage of iterators over lists is that using iterators does not have to add the list to the memory at once, but can access the data of the list sequentially.
Still use the above method to view the public methods of the iterator:
lst = [1,2,3,4,5] lstiter = iter(lst) print [x for x in dir(numiter) if not x.startswith("__")] >>>['next']
Yes, there is only one method next. For an iterator, you can do this:
lst = [1,2,3,4,5] lstiter = iter(lst) for i in range(len(lst)): print lstiter.next() #依次打印 1 2 3 4 5
Tuple type
The tuple type, like the list, is also a sequence. Unlike the list, the tuple type cannot be modified. The declaration of the tuple is as follows:
lst = (0,1,2,2,2) lst1=("hello",) lst2 = ("hello") print type(lst1) #只有一个元素的情况下后面要加逗号 否则就是str类型 print type(lst2) #
Dictionary type
The dictionary type is a collection of key-value pairs, similar to Dictionary6c3c0e4ab25bd75a295015325220c902 or json object in js. Its initialization method is as follows:
dict1 = {} print type(dict1) #声明一个空字典 dict2 = {"name":"kitty","age":18} #直接声明字典类型 dict3 = dict([("name","kitty"),("age",18)]) #利用dict函数将列表转换成字典 dict4 = dict(name='kitty',age=18) #利用dict函数通过关键字参数转换为字典 dict5 = {}.fromkeys(["name","age"]) #利用fromkeys函数将key值列表生成字典,对应的值为None {'age': None, 'name': None} 字典基本的操作方法: #【添加元素】 dict1 = {} dict1["mykey"] = "hello world" #直接给一个不存在的键值对赋值 即时添加新元素 dict1[('my','key')] = "this key is a tuple" #字典的键可以是任何一中不可变类型,例如数字、字符串、元组等 #【键值对个数】 print len(dict1) #【检查是否含有键】 print "mykey" in dict1 #True 检查是否含有键为mykey的键值对 print "hello" in dict1 #False #【删除】 del dict1["mykey"] #删除键为mykey的键值对
继续利用上面的方法查看字典的所有公共方法:
>>> [x for x in dir({}) if not x.startswith("__")] ['clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues'] dict.clear() 删除字典中所有元素 dict.copy() 返回字典(浅复制)的一个副本 dict.get(key,default=None) 对字典dict 中的键key,返回它对应的值value,如果字典中不存在此键,则返回default 的值(注意,参数default 的默认值为None) dict.has_key(key) 如果键(key)在字典中存在,返回True,否则返回False. 在Python2.2版本引入in 和not in 后,此方法几乎已废弃不用了,但仍提供一个 可工作的接口。 dict.items() 返回一个包含字典中(键, 值)对元组的列表 dict.keys() 返回一个包含字典中键的列表 dict.values() 返回一个包含字典中所有值的列表 dict.iter() 方法iteritems(), iterkeys(), itervalues()与它们对应的非迭代方法一样,不同的是它们返回一个迭代器,而不是一个列表。 dict.pop(key[, default]) 和方法get()相似,如果字典中key 键存在,删除并返回dict[key],如果key 键不存在,且没有给出default 的值,引发KeyError 异常。 dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。 dict.setdefault(key,default=None) 和方法set()相似,如果字典中不存在key 键,由dict[key]=default 为它赋值。
布尔类型
布尔类型即True和False,和其它语言中的布尔类型基本一致。下面列出典型的布尔值
print bool(0) #False print bool(1) #True print bool(-1) #True print bool([]) #False print bool(()) #False print bool({}) #False print bool('') #False print bool(None) #False
推荐教程:《python教程》
The above is the detailed content of What are the python data types?. For more information, please follow other related articles on the PHP Chinese website!