Home Backend Development Python Tutorial Summary of data types in Python

Summary of data types in Python

Jun 20, 2017 pm 02:26 PM
python Base data type

1. Integer type

In Python2, there are integer types and long integer types, but in Python3, the long integer type is canceled and classified as integer type.

Integers in Python can be expressed in binary, octal, decimal and hexadecimal forms

You can use the following method to convert decimal to other forms

>>> print(bin(10))           --------->  把十进制转化为二进制
0b1010>>> print(oct(10))           --------->  把十进制转化为八进制
0o12>>> print(hex(10))           --------->  把十进制转化为十六进制0xa>>> print(hex(100))0x64
Copy after login

二、浮点型

浮点型数就是小数,因为用科学计数法表示小数时,小数点的位置是可以变化的,所以称为浮点数。在计算机中,整数永远是准确的,而浮点数在四舍五入的过程中却有可能产生误差。小的浮点数可以直接写,但是对于位数很多的浮点数,就必须用科学计数法来表示。把10用e表示,如1.03乘10的9次方,就要写成1.03e9

三、字符串类型

定义在引号里面的整体称为字符串,是由一个个字符构成的

引号可以是单引号,双引号,三引号,多引号...(在Python中,单引号和双引号没有区别)

字符串的常用操作:

Python为字符串内置了很多种方法,方便处理需求

1..strip()    作用是移除空白,可以在()中指定移除的字符,默认为空格

x='*****abc*****'
print(x.strip('*'))

运行结果为:abc
Copy after login

2..capitalize()   作用是首字母大写

x='hello world'
print(x.capitalize())

运行结果为:Hello world
Copy after login

3.upper()       作用是所有字母都大写,相反的lower()的作用是所有字母小写

x='hello world'
print(x.upper())

运行结果为:HELLO WORLD
Copy after login

4..center(self,width,fillchar)       作用是把字符放中间,左右用指定的字符填充至指定的字符长度

x='hello world'
print(x.center(30,'*'))

 运行结果为:*********hello world*********
Copy after login
5..count      作用是统计字符串中某一字符出现的次数,可以指定范围
Copy after login
x='hello world'
print(x.count('l',0,10))       命令的作用是统计“hello world”中第1到11个字符中,‘l’出现的次数
运行结果为:3

6..startswith()      以..开头
  x='hello world'
  print(x.startswith('a'))       判断x是否以‘a’开头,如果是,结果为True,如果不是,结果为False
Copy after login
 .endswith()         以..结尾

7..find()          寻找,如果结果不为负数,则成功。会返回目标字符在字符串中的位置
             find()和index()的区别是如果找不到对象,find()会返回-1,index()会报错

8..format        格式化字符串(先举个小例子,后续博客中会详细介绍)
  x='myname:{},age:{},sex:{}'
   print(x.format('zhang',18,'male'))
  
  运行结果为:myname:zhang,age:18,sex:male

9..index()   查看某个字符的索引,如果超出范围会报错
  x='hello world'
  print(x[1])           ------>e
  print(x[4])           ------>o
  print(x[-1])          ------>d     倒着数
  print(x.index('w'))    --------->6   查看某一字符在在字符串中的索引

  字符串的切片操作:print(x[1:3])     -------->el    取x中第1,2个字符
    切片也可以加步长:print(x[1:5:2])   ------->el   取x中第1,2,3,4个字符,但是每两个字符取一次,也就是取第1,3个字符   

10..isdigit()     查看字符串是否为整数,是则输出True,否则输出False
  x='hello world'
  print(x.isdigit())
  
  False

11..replace      替换

   x='hello world'
   print(x.replace('e','E'))        #不止可以替换字符,也可以替换字符串

 运行结果为:hEllo world

12..split()         默认以空格为分隔符分割成几部分,当然也可以指定字符作为分隔符
  
  x='hello:world:today:is:a:goodday'
   print(x.split(':'))

  运行结果为:['hello', 'world', 'today', 'is', 'a', 'goodday']

13..issupper()    判断是否全部为大写
  .islower()     判断是否全部为小写
  .isspace()     判断是否为空格
  .istitle()     判断是否首字母大写

14..ljust()       左对齐
  .rjust()       右对齐

15..swapcase()    大小写反转
  .title()       首字母大写
Copy after login

四、列表 list

 列表中可以存放各种数据类型,以逗号分割开,每个位置存放一个元素

1.列表的特性:可以存放多个值,每个值对应一个索引值

       列表中的值可变

       按从左到右的顺序定义列表元素,下标从0开始,是有序的

2.列表的创建

l=['abc','123',12]           ------>['abc', '123', 12]

l=list('abc123')         ------>['a', 'b', 'c', '1', '2', '3']

l=list(['abc','123',12])               ------->['abc', '123', 12]

 

3.列表的常用操作

1)索引

l=['abc','123',12,[3,'e',5]]

print(l[0])          -------->abc

print(l[2])    ---------->12

print(l[3][2])     ----------->5

2) 切片

l=['abc','123',12,'[3,'e',5]]

print(l[1:3])           --------->['123', 12]

注意:切片是读操作,原列表并不会发生改变

3)追加 .append()

l=['abc','123',12,'[3,'e',5]]

l.append('hello')

print(l)         ------------>['abc', '123', 12, [3, 'e', 5], 'hello']

默认是把字符加在原列表最后边

4)插入  .insert()

l=['abc','123',12,'[3,'e',5]]

l.insert(0,'hello')

print(l)       ------------>['hello', 'abc', '123', 12, [3, 'e', 5]] 

注意:insert()中要指定索引位置,必须指定,否则会报错

5)删除 .pop()

l=['abc','123',12]

l.pop(1)

print(l)     ------------>['abc', 12]

注意:()中可以指定要删除的元素的索引值,默认是最后一个

   l.pop()是有返回值的,返回删掉的元素

补充:队列和堆栈

队列是先进先出,可以用append()和pop(0) 或 insert()和pop()模拟

堆栈是先进后出,可以用append()和pop() 或insert()和pop(0)模拟

6)长度 len()

l=[1,2,3]

print(len(l))    ---------------------->3

7)循环

l=[1,2,3]

for i in l:

print(i)           --------------------->1  2  3

8)包含 in

l=['a','b','c']     

print('b' in l)  ------------------------->True

4.列表的其他操作

1)查看某一元素的索引 .index()

l=['a','b','c']

print(l.index('a'))    ------------------>0

2)列表中某个元素的数量 .count()

l=['a','b','c','a']

print(l.count('a))    -------------->2

3)追加 .extend() 和append有区别

l=[1,2,3]
l.append(['a','b','c'])
print(l)    -------------->[1, 2, 3, ['a', 'b', 'c']]
Copy after login
l=[1,2,3]
l.extend(['a','b','c'])
print(l)    --------------->[1, 2, 3, 'a', 'b', 'c']
Copy after login

4)按元素删除 .remove 

 注意当目标元素不存在时会报错,且有多个目标元素时只会删一个

l=[1,2,3]
l.remove('a')
print(l)      ------------->ValueError: list.remove(x): x not in list
Copy after login

5)排序 .sort()   无返回值

l=[3,2,4]
l.sort()
print(l)    ----------------->[2, 3, 4]
Copy after login
l=['a','c','d','cd']
l.sort()
print(l)    ----------------->['a', 'c', 'cd', 'd']

l.sort(reverse=True) 表示倒序排列
Copy after login

6)反转顺序 .reverse()

 

五、元组 tuple

1)元组的定义

t=('a','b',1,(3,4))

形式与列表相似,只是[]改成了()

2)元组的特性:

元组元素可以是任意数据类型;

元组是不可变数据类型;

元组的元素可以是列表,列表的元素可以变,虽然列表的元素改变了,但是列表作为元组的一个元素并没有发生变化,所以不影响元组是不可变数据类型这一特点

因为元组是不可变数据类型,所以不存在增删改的功能,元组的方法只有count() 和 index()

3)元组的常用操作有:索引、切片、循环、长度和包含

4)元组和列表的相互转化:  

t=('a','b',1,2)
l=['f','d',4]

tl=list(tuple(t))
print(tl,type(tl))    ---------->['a', 'b', 1, 2] <class &#39;list&#39;>

lt=tuple(list(l))
print(lt,type(lt))    ---------->('f', 'd', 4) <class &#39;tuple&#39;>
Copy after login

六、字典 dict

1)字典的定义:

d={'x':1,'y':1234}
Copy after login

2)字典的元素是键值对(key - values)

 字典是一种可变数据类型,其中values可变,但是Key不可变

 需注意:定义字典时,key必须是不可变类型,或者说是可hash类型

3)字典的取值

 字典是无序的,没有索引的概念,通过key来取值 print(d['x']) 就能取到1这个值

 如果key找不到的话会报错,可以用.get(key)   如果找不到key,会打印None,但是不会报错 

4)修改值

 d['x']='s'  --------把原字典改成了{‘x’:'s','y':1234}

5)循环 

d={'name':'zhang','age':18}
print(d.keys())                 #dict_keys(['name', 'age'])
print(d.values())               #dict_values(['zhang', 18])
for i in d:
    print(i)                    #name age  直接遍历字典,打印的是key
for k in d:
    print(k,d[k])               #name zhang   age 18
Copy after login

 因为字典是无序的,所以遍历字典的方法只有 for i in d:这一种

字典的常用方法:

1)清除

d={'x':1}
d.clear()      #清除
print(d)       #{}
Copy after login

2)避免找不到元素报错的情况

d={'x':1}
print(d.get('s'))       #None
print(d('s'))             #报错TypeError: 'dict' object is not callable
Copy after login

3)把键值对转换成元组形式

d={'x':1}
d.items()
for k,v in d.items():
    print(k,v)          #x 1
Copy after login

4)把values转换成列表形式

d={'x':1,'y':2322}
print(list(d.values()))      #把values值转换成列表形式----------->[1, 2322]
Copy after login

5)删除 .pop()

d={'x':1,'y':2322}
d.pop('x')
print(d)                      #{'y': 2322}
print(d.pop('x'))               #1    打印删除的那个值
Copy after login

6)删除 .popitem()  随机删除

d={'x':1,'y':2322}
d.popitem()             #括号里不能跟参数,随机删除
print(d)                #{'x': 1}
Copy after login

7)添加键值对 .setdefault()  括号里是键值对

d={'x':1}
d.setdefault('s',2)             
print(d)            #{'x': 1, 's': 2}      添加键值对,key和值之间用逗号隔开
Copy after login

8)产生字典的方法

d3=dict(x=5,y=2,z=3)                  #{'x': 5, 'y': 2, 'z': 3}   自动生成字典
d3=dict({'x':1,'y':2})                  #{'x': 1, 'y': 2}
d3=dict([('x',1),('y',2),('z',3)])      #{'x': 1, 'y': 2, 'z': 3}
d3={}.fromkeys(['name','age'],None)     #{'name': None, 'age': None}    None的位置只能有一个值,这种方法只能创建这种类型的
print(d3)
Copy after login

9)更新字典 .update()

d={'name':'alex'}
d1={'name':'alexsb','age':30}
d.update(d1)                    #用d1更新字典d
print(d)                    #{'name': 'alexsb', 'age': 30}
Copy after login

10)长度

d={'name':'zhangcan','age':18,'salary':'100000'}
print(len(d))                   #3
print(len(d.values()))          #3
print(len(d.items()))           #3
print(len(d.keys()))            #3
Copy after login

11)成员运算

d={'name':'zhangcan','age':18,'salary':'100000'}
print('x'in d)                                      #False
print('name'in d)                                   #True
print(18 in d)                            #False
print(18 in d.values())                      #True
print('age' in d.keys())                     #True
print(18 in d.items())                       #False
print(('age',18) in d.items())                #True
Copy after login

七、布尔类型

所有的数据类型都自带布尔值(bool),if 判断时,只有0,None,NULL为False,其他都为True

八、集合(set)
1.集合的定义

 1)集合内的元素必须是唯一的,可以用这个特性来实现‘去重’的功能  

  s={'egon',123,123,1,'abf'}
  print(s)           # {1, 123, 'egon', 'abf'}
Copy after login

 2)集合内的元素必须是可hash的,即不可变的

 3)集合是无序的(无索引)

2.集合的关系运算(符号)

s1={'alex','egon','wupeiqi'}
s2={'alex','egon','zhangcan'}
print(s1 & s2)      #取交集
print(s1 | s2)      #取并集
print(s1-s2)        #差集{'wupeiqi'}
print(s1^s2)        #对称差集{'zhangcan', 'wupeiqi'}
Copy after login

3.集合的常用命令

print(s1.difference(s2))    #差集
print(s1.intersection(s2)) # 交集
print(s1.union(s2))         #并集
print(s1.symmetric_difference(s2))  #{'zhangcan', 'wupeiqi'}对称差集
print(s1.symmetric_difference_update(s2))  #None对称差集并更新回s1
print(s1)                                   #{'zhangcan', 'wupeiqi'}
Copy after login
s1.update(s2)       #并集
print(s1)           #{'zhangcan', 'wupeiqi', 'egon', 'alex'}
Copy after login
s1.add('yuanhao')       #添加元素
print(s1)
Copy after login
s1.discard('alex')          #删除(找不到元素不会报错)
print(s1)

s1.remove('alex')          #删除,但找不到元素会报错
Copy after login
s1.pop()         #括号里不能有东西,随机删除
print(s1)
Copy after login

成员运算:

s3={'a','b','c',1,2,3}
s4={1,2,3}
print(s4.issubset(s3))     #s4是否是s3的子集
print(s3.issuperset(s4))    #s3是否是s4的超集
print(s3.isdisjoint(s4))    #s3和s4是否有交集,有交集---False,没有交集---True
Copy after login

 

The above is the detailed content of Summary of data types in Python. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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)

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles