Home > Backend Development > Python Tutorial > What are the python data types?

What are the python data types?

烟雨青岚
Release: 2020-07-13 09:52:06
Original
46638 people have browsed it

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).

What are the python data types?

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)  
<type &#39;int&#39;>
Copy after login
>>> i=10000000000  
>>> type(i)  
<type &#39;long&#39;>
Copy after login

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
Copy after login

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 &#39;int&#39;>  
>>> type(2147483648)  
<type &#39;long&#39;>
Copy after login

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)  
<type &#39;float&#39;>
Copy after login

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 = &#39;hello world&#39;  
>>> str2 = "hello world"  
>>> str3 = &#39;&#39;&#39;hello world&#39;&#39;&#39;  
>>> str4 = """hello world"""  
>>> print str1  
hello world  
>>> print str2  
hello world  
>>> print str3  
hello world  
>>> print str4  
hello world
Copy after login

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  
中国
Copy after login

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&#39;汉&#39;  
print repr(u) # u&#39;\u6c49&#39;  
s = u.encode(&#39;UTF-8&#39;)  
print repr(s) # &#39;\xe6\xb1\x89&#39;  
u2 = s.decode(&#39;UTF-8&#39;)  
print repr(u2) # u&#39;\u6c49&#39;  
解释:声明unicode字符串”汉“,它的unicode编码为”\u6c49“,经过utf-8编码转换后,它的编码变成”\xe6\xb1\x89“。
Copy after login

Summary of coding experience:

1. Declare the encoding format in the python file header;

#-*- coding: utf-8 -*-
Copy after login

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
Copy after login

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(&#39;utf-8&#39;)  
    print "utf-8"  
else:  
    print content.decode(&#39;gbk&#39;).encode(&#39;utf-8&#39;)
Copy after login

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)  
<type &#39;list&#39;>  
>>> print nums  
[1, 2, 3, 4]  
>>> strs = ["hello","world"]  
>>> print strs  
[&#39;hello&#39;, &#39;world&#39;]  
>>> lst = [1,"hello",False,nums,strs]  
>>> type(lst)  
<type &#39;list&#39;>  
>>> print lst  
[1, &#39;hello&#39;, False, [1, 2, 3, 4], [&#39;hello&#39;, &#39;world&#39;]]
Copy after login

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]
Copy after login

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, &#39;three&#39;, &#39;four&#39;, 4, 5]  在3和4之间插入  
  
nums[3:5] = []    #[1, 2, 3, 4, 5] 将第4和第5个元素替换为[] 即删除["three","four"]  
支持加法和乘法操作
lst1 = ["hello","world"]  
lst2 = [&#39;good&#39;,&#39;time&#39;]  
print lst1+lst2  #[&#39;hello&#39;, &#39;world&#39;, &#39;good&#39;, &#39;time&#39;]  
  
print lst1*5  #[&#39;hello&#39;, &#39;world&#39;, &#39;hello&#39;, &#39;world&#39;, &#39;hello&#39;, &#39;world&#39;, &#39;hello&#39;, &#39;world&#39;, &#39;hello&#39;, &#39;world&#39;]
Copy after login

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("__")]  
[&#39;append&#39;, &#39;count&#39;, &#39;extend&#39;, &#39;index&#39;, &#39;insert&#39;, &#39;pop&#39;, &#39;remove&#39;, &#39;reverse&#39;, &#39;sort&#39;]  
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, &#39;hello&#39;, &#39;world&#39;]  在lst的基础上扩展了lstextend进来   
  
#【index】  返回某个值第一次出现的索引位置,如果未找到会抛出异常  
print lst.index("hello")  #5      
  
#print lst.index("kitty") #ValueError: &#39;kitty&#39; is not in list  出现异常  
  
  
#【remove】 移除列表中的某个元素,如果待移除的项不存在,会抛出异常  无返回值  
lst.remove("hello")  
print lst     #[2, 3, 4, 5, 6, &#39;world&#39;]  "hello" 被移除  
  
#lst.remove("kitty")         #ValueError: list.remove(x): x not in list  
  
#【reverse】  意为反转 没错 就是将列表元素倒序排列,无返回值  
print lst        #[2, 3, 4, 5, 6, &#39;world&#39;]  
lst.reverse()   
print lst        #[2, 3, 4, 5, 6, &#39;world&#39;]  
  
  
#【sort】 排序  
print lst    #由于上面的反转 目前排序为 [&#39;world&#39;, 6, 5, 4, 3, 2]  
lst.sort()    
print lst    #排序后  [2, 3, 4, 5, 6, &#39;world&#39;]  
  
nums = [10,5,4,2,3]  
print nums     #[10,5,4,2,3]  
nums.sort(compare)  
print nums     #[2, 3, 4, 5, 10]
Copy after login

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("__")]  
>>>[&#39;next&#39;]
Copy after login

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
Copy after login

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)    #<type &#39;tuple&#39;>  只有一个元素的情况下后面要加逗号 否则就是str类型  
print type(lst2)    #<type &#39;str&#39;>
Copy after login

Dictionary type

The dictionary type is a collection of key-value pairs, similar to Dictionary or json object in js. Its initialization method is as follows:

dict1 = {}  
print type(dict1)      #<type &#39;dict&#39;>  声明一个空字典  
  
dict2 = {"name":"kitty","age":18}   #直接声明字典类型  
  
dict3 = dict([("name","kitty"),("age",18)])  #利用dict函数将列表转换成字典  
  
dict4 = dict(name=&#39;kitty&#39;,age=18)           #利用dict函数通过关键字参数转换为字典  
  
dict5 = {}.fromkeys(["name","age"])      #利用fromkeys函数将key值列表生成字典,对应的值为None   {&#39;age&#39;: None, &#39;name&#39;: None}  
字典基本的操作方法:
#【添加元素】    
dict1 = {}  
dict1["mykey"] = "hello world"     #直接给一个不存在的键值对赋值 即时添加新元素  
  
dict1[(&#39;my&#39;,&#39;key&#39;)] = "this key is a tuple"   #字典的键可以是任何一中不可变类型,例如数字、字符串、元组等  
  
#【键值对个数】  
print len(dict1)  
  
#【检查是否含有键】  
print "mykey" in dict1         #True  检查是否含有键为mykey的键值对  
print "hello" in dict1         #False  
  
#【删除】  
del dict1["mykey"]           #删除键为mykey的键值对
Copy after login

继续利用上面的方法查看字典的所有公共方法:

>>> [x for x in dir({}) if not x.startswith("__")]  
[&#39;clear&#39;, &#39;copy&#39;, &#39;fromkeys&#39;, &#39;get&#39;, &#39;has_key&#39;, &#39;items&#39;, &#39;iteritems&#39;, &#39;iterkeys&#39;, &#39;itervalues&#39;,  
 &#39;keys&#39;, &#39;pop&#39;, &#39;popitem&#39;, &#39;setdefault&#39;, &#39;update&#39;, &#39;values&#39;, &#39;viewitems&#39;, &#39;viewkeys&#39;, &#39;viewvalues&#39;]  
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 为它赋值。
Copy after login

布尔类型

布尔类型即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(&#39;&#39;)  #False  
print bool(None) #False
Copy after login

推荐教程:《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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template