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

What are the python data types?

Jul 13, 2020 am 09:51 AM
python

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

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

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;>

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

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&#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“。

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

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;]]

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, &#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;]

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]

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;]

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

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的键值对

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

>>> [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 为它赋值。

布尔类型

布尔类型即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

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

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1504
276
python connect to sql server pyodbc example python connect to sql server pyodbc example Jul 30, 2025 am 02:53 AM

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

python django forms example python django forms example Jul 27, 2025 am 02:50 AM

First, define a ContactForm form containing name, mailbox and message fields; 2. In the view, the form submission is processed by judging the POST request, and after verification is passed, cleaned_data is obtained and the response is returned, otherwise the empty form will be rendered; 3. In the template, use {{form.as_p}} to render the field and add {%csrf_token%} to prevent CSRF attacks; 4. Configure URL routing to point /contact/ to the contact_view view; use ModelForm to directly associate the model to achieve data storage. DjangoForms implements integrated processing of data verification, HTML rendering and error prompts, which is suitable for rapid development of safe form functions.

Optimizing Python for Memory-Bound Operations Optimizing Python for Memory-Bound Operations Jul 28, 2025 am 03:22 AM

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

python shutil rmtree example python shutil rmtree example Aug 01, 2025 am 05:47 AM

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? What is statistical arbitrage in cryptocurrencies? How does statistical arbitrage work? Jul 30, 2025 pm 09:12 PM

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

python psycopg2 connection pool example python psycopg2 connection pool example Jul 28, 2025 am 03:01 AM

Use psycopg2.pool.SimpleConnectionPool to effectively manage database connections and avoid the performance overhead caused by frequent connection creation and destruction. 1. When creating a connection pool, specify the minimum and maximum number of connections and database connection parameters to ensure that the connection pool is initialized successfully; 2. Get the connection through getconn(), and use putconn() to return the connection to the pool after executing the database operation. Constantly call conn.close() is prohibited; 3. SimpleConnectionPool is thread-safe and is suitable for multi-threaded environments; 4. It is recommended to implement a context manager in combination with context manager to ensure that the connection can be returned correctly when exceptions are noted;

python iter and next example python iter and next example Jul 29, 2025 am 02:20 AM

iter() is used to obtain the iterator object, and next() is used to obtain the next element; 1. Use iterator() to convert iterable objects such as lists into iterators; 2. Call next() to obtain elements one by one, and trigger StopIteration exception when the elements are exhausted; 3. Use next(iterator, default) to avoid exceptions; 4. Custom iterators need to implement the __iter__() and __next__() methods to control iteration logic; using default values is a common way to safe traversal, and the entire mechanism is concise and practical.

How to execute SQL queries in Python? How to execute SQL queries in Python? Aug 02, 2025 am 01:56 AM

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

See all articles