Home > Backend Development > Python Tutorial > What are the basic data types of Python and how to use them

What are the basic data types of Python and how to use them

王林
Release: 2023-05-23 19:43:04
forward
2213 people have browsed it

Part 1 Number Types

1.1 Composition of Number Types

1.1.1 Integer - Conversion of different bases
  • The default input is decimal

  • Binary 0b, Octal 0o, Hexadecimal 0x

16 == 0b10000 == 0o20 == 0x10
Copy after login
rrree
  • Conversion between decimal and other bases

True
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
a = bin(16)   # 转二进制
b = oct(16)   # 转八进制
c = hex(16)   # 转十六进制
print(a, b, c)
Copy after login

Note: The result after the above conversion is of string type, so if an equality comparison is performed, the output is False result

0b10000 0o20 0x10
Copy after login
a == b == c
Copy after login
False
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
type(a)
Copy after login
  • Convert other bases to decimal

str
Copy after login
d = int(a, 2)      # 二进制转十进制
e = int(b, 8)      # 八进制转十进制
f = int(c, 16)     # 十六进制转十进制
print(d, e, f)
Copy after login
1.1.2 Floating point number - uncertainty
  • Uncertain decimal problem

16 16 16
Copy after login
(0.1+0.2) == 0.3
Copy after login
False
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
0.1+0.2
Copy after login

Computers use binary decimals to represent the decimal part of floating point numbers

  • Reason: Some decimals cannot be completely represented by binary decimals

0.30000000000000004
Copy after login
Copy after login

0.00011001100110011001 0.09999942779541016 0.0011001100110011 0.1999969482421875 0.01001100110011001 0.29999542236328125 0.01100110011001101 0.40000152587890625 0.1 ===   ===   0.5

  • Normally it will not affect the calculation accuracy

二进制                  十进制
Copy after login
0.1 + 0.7
Copy after login
  • Round to get the accuracy Solution

  • can be solved by rounding: round(parameter, retain the number of decimal places)

  • ##
0.7999999999999999
Copy after login
a = 3*0.1
print(a)
Copy after login
0.30000000000000004
Copy after login
Copy after login
b = round(a, 1)
print(b)
b == 0.3
Copy after login
1.1.3 Complex numbers - a bj
  • Uppercase J or lowercase j can be used

0.3



True
Copy after login
3+4j
2+5J
Copy after login
  • When the imaginary part coefficient is 1, it needs to be written explicitly

(2+5j)
Copy after login
1.2 Numeric operation operators (a operator b)

  • Addition, subtraction, multiplication and division operations    -  /  *

2+1j
Copy after login
(1+3-4*2)/5
Copy after login
  • Inversion-

-0.8
Copy after login
x = 1
-x
Copy after login
  • Power operation**

-1
Copy after login
2**3
Copy after login
  • Integer quotient//and modular operation%

8
Copy after login
13//5    # 整数商    x/y 向下取整数
Copy after login
2
Copy after login
Copy after login
Copy after login

A few notes

  • The result of the operation between integers and floating point numbers is a floating point number

  • The result of the division operation is a floating point number

13 % 5   # 模运算    余数 13=2*5+3
Copy after login
1+1.5
Copy after login
2.5
Copy after login
2/5
Copy after login
0.4
Copy after login
8/4
Copy after login
1.3 Numerical operation function function(x, ...)

  • Find the absolute value abs()

2.0
Copy after login
abs(-5)
Copy after login
5
Copy after login
abs(3+4j)  # 对复数a+bj 执行的是求模运算(a^2+b^2)^0.5
Copy after login
  • power Power pow(x,n)

  • Power power modulo pow(x,n,m)

5.0
Copy after login
pow(2, 5)  # pow(x,n) x的n次方  等价于x**n
Copy after login
32
Copy after login
pow(2, 5, 3) # 2^5 % 3  更快速
Copy after login
  • Rounding round(x,n)

2
Copy after login
Copy after login
Copy after login
a = 1.618
print(round(a))      # 默认四舍五入为整数
Copy after login
2
Copy after login
Copy after login
Copy after login
print(round(a, 2))   # 参数2表示四舍五入后保留2位小数
Copy after login
1.62
Copy after login
print(round(a, 5))   # 位数不足,无需补齐
Copy after login
  • Integer quotient and modular operation divmod(x,y)

Equivalent to returning a tuple (x//y,x % y)

1.618
Copy after login
divmod(13, 5)   # 较(x//y,x % y)更快,只执行了一次x/y
Copy after login
  • Maximum/minimum value of the sequence max( )  min( )

(2, 3)
Copy after login
max(3, 2, 3, 6, 9, 4, 5)
Copy after login
9
Copy after login
a = [3, 2, 3, 6, 9, 4, 5]
print("max:", max(a))
print("min:", min(a))
Copy after login
  • Sum sum(x)

Note: A sequence data needs to be filled in sum

max: 9
min: 2
Copy after login
sum((1, 2, 3, 4, 5))
Copy after login
  • With the help of the scientific computing library math\scipy\numpy

15
Copy after login
import math   # 导入库
print(math.exp(1))   # 指数运算 e^x
print(math.log2(2))  # 对数运算
print(math.sqrt(4))  # 开平方运算  等价于4^0.5
Copy after login
2.718281828459045
1.0
2.0
Copy after login
import numpy as np
a = [1, 2, 3, 4, 5]
print(np.mean(a))    # 求均值
print(np.median(a))  # 求中位数
print(np.std(a))     # 求标准差
Copy after login
Part 2 String Type

2.1 Expression of String

  • Any characters enclosed by "" or ''

3.0
3.0
1.4142135623730951
Copy after login
print("Python")
print('Python')
Copy after login
  • When there are double quotes or single quotes in the string

There is an odd in the double

Python
Python
Copy after login
print("I'm 18 years old")
Copy after login

There is a double in the odd

print('"Python" is good')
Copy after login
"Python" is good
Copy after login
Copy after login

双中有双,单中有单——转义符   \

# print(""Python" is good")
print("\"Python\" is good")  # \ 字符
Copy after login
"Python" is good
Copy after login
Copy after login

转义符可以用来换行继续输入

s = "py\
thon"                    
print(s)
Copy after login
python
Copy after login

2.2 字符串的性质

2.2.1 字符串的索引
s = "My name is Peppa Pig"
Copy after login
Copy after login

变量名[位置编号]

  • 正向索引——从零开始递增

  • 位置编号不能超过字符串的长度

  • 空格也是一个位置

print(s[0])   
print(s[2])
print(s[5])
Copy after login
M
 
m
Copy after login
s = "My name is Peppa Pig"
Copy after login
Copy after login
  • 反向索引——从-1开始递减

print(s[-1])
print(s[-3])
print(s[-5])
Copy after login
g
P
a
Copy after login

索引只能获得一个字符,如何获得多个字符?

2.2.2 字符串的切片

变量名[开始位置:结束位置:切片间隔]

  • 切片间隔如不设置默认为1,可省略

  • 切片范围不包含结束位置(前闭后开)

s = "Python"
print(s[0:3:1])
Copy after login
Pyt
Copy after login
Copy after login
print(s[0:3])
Copy after login
Pyt
Copy after login
Copy after login
print(s[0:3:2])
Copy after login
Pt
Copy after login
  • 起始位置是0 可以省略

  • 结束位置省略,代表可以取到最后一个字符

  • 可以使用反向索引

s = "Python"
print(s[0:6])
Copy after login
Python
Copy after login
Copy after login
Copy after login
Copy after login
print(s[:6])
Copy after login
Python
Copy after login
Copy after login
Copy after login
Copy after login
print(s[:])
Copy after login
Python
Copy after login
Copy after login
Copy after login
Copy after login
print(s[-6:])
Copy after login
Python
Copy after login
Copy after login
Copy after login
Copy after login

反向切片

  • 起始位置是-1也可以省略

  • 结束位置省略,代表可以取到第一个字符

  • 关键点在于-1,代表前一个位置比后一个位置大-1

s = "123456789"
print(s[-1:-10:-1])
Copy after login
987654321
Copy after login
Copy after login
Copy after login
print(s[:-10:-1])
Copy after login
987654321
Copy after login
Copy after login
Copy after login
print(s[::-1])
Copy after login
987654321
Copy after login
Copy after login
Copy after login

2.3 字符串操作符

2.3.1 字符串的拼接
  • 字符串1+字符串2

a = "I love "
b = "my wife "
a+b
Copy after login
'I love my wife '
Copy after login
2.3.2 字符串的成倍复制
  • 字符串 * n   n * 字符串

c = a+b
print(c*3)
print(3*c)
Copy after login
I love my wife I love my wife I love my wife 
I love my wife I love my wife I love my wife
Copy after login
2.2.3 成员运算
  • 子集in全集   任何一个连续的切片都是原字符串的子集

folk_singers = "Peter, Paul and Mary"    
"Peter" in folk_singers
Copy after login
True
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
"PPM" in folk_singers
Copy after login
False
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
  • 遍历字符串字符   for 字符 in 字符串

for s in "Python":
    print(s)
Copy after login
P
y
t
h
o
n
Copy after login

2.4 字符串处理函数

2.4.1 字符串的长度
  • 所含字符的个数

s = "python"
len(s)
Copy after login
6
Copy after login
2.4.2 字符编码

将中文字库,英文字母、数字、特殊字符等转化成计算机可识别的二进制数

  • 每个单一字符对应一个唯一的互不重复的二进制编码

  • Python 中使用的是Unicode编码

将字符转化为Unicode码——ord(字符)

print(ord("1"))
print(ord("a"))
print(ord("*"))
print(ord("中"))
print(ord("国"))
Copy after login
49
97
42
20013
22269
Copy after login

将Unicode码转化为字符——chr(Unicode码)

print(chr(1010))
print(chr(10000))
print(chr(12345))
print(chr(23456))
Copy after login
ϲ
✐
〹
宠
Copy after login

2.5 字符串的处理方法

2.5.1 字符串的分割——字符串.split(分割字符)
  • 返回一个列表

  • 原字符串不变

上述特性适合以下所有字符串处理方法

languages = "Python C C++ Java PHP R"
languages_list = languages.split(" ")#括号里的参数就是我们希望对目标字符串进行分割的标记
print(languages_list)
print(languages)
Copy after login
['Python', 'C', 'C++', 'Java', 'PHP', 'R']
Python C C++ Java PHP R
Copy after login
2.5.2  字符串的聚合——“聚合字符”.join(可迭代数据类型)
  • 可迭代类型 如:字符串、列表

s = "12345"
s_join = ",".join(s) #把可迭代的对象每一个都取出来,相邻两个之间加上聚合字符
s_join
Copy after login
'1,2,3,4,5'
Copy after login
  • 序列类型的元素必须是字符类型

# s = [1, 2, 3, 4, 5] 无法使用聚合
s = ["1", "2", "3", "4", "5"]
"*".join(s)
Copy after login
'1*2*3*4*5'
Copy after login
3.5.3 删除两端特定字符——字符串.strip(删除字符)
  • strip从两侧开始搜索,遇到指定字符执行删除,遇到非指定字符,搜索停止

  • 类似的还有左删除lstrip和右删除rstrip

s = "      I have many blanks     "
print(s.strip(" "))                        #从两端进行搜索,遇到指定字符后删除空格,然后停止
print(s.lstrip(" "))
print(s.rstrip(" "))
print(s)
Copy after login
I have many blanks
I have many blanks     
      I have many blanks
      I have many blanks
Copy after login
3.5.4 字符串的替换——字符串.replace("被替换","替换成")
s = "Python is coming"
s1 = s.replace("Python","Py")
print(s1)
Copy after login
Py is coming
Copy after login
3.5.5 字符串统计——字符串.count("待统计字符串")
s = "Python is an excellent language"
print("an:", s.count("an"))
print("e:", s.count("e"))
Copy after login
an: 2
e: 4
Copy after login
3.3.6 字符串字母大小写
  • 字符串.upper() 字母全部大写

s = "Python"
s.upper()
Copy after login
'PYTHON'
Copy after login
  • 字符串.lower() 字母全部小写

print(s.lower())
print(s)
Copy after login
python
Python
Copy after login
  • 字符串.title()首字母大写

s.title()
Copy after login
'Python'
Copy after login

第三部分 布尔类型TRUEorFalse

3.1 逻辑运算的结果

a = 10
print(a > 8)
print(a == 12)
print(a < 5)
Copy after login
True
False
False
Copy after login
  • any() 数据有一个是非零就为True

  • all() 数据有一个是零就为False (元素都是非零的)

print(any([False,1,0,None]))   # 0 False None 都是无
print(all([False,1,0,None]))
Copy after login
True
False
Copy after login

3.2 指示条件

n = 2800
while True:
    m = eval("请输入一个正整数:"))
    if m == n:
        print("正确")
        break
    elif m > n:
        print("太大了")
    else:
        print("太小了")
Copy after login
请输入一个正整数:280
太小了
请输入一个正整数:2800
正确
Copy after login

3.3 作为numpy数组的掩码

import numpy as np
x = np.array([[1, 3, 2, 5, 7]])   # 定义 numpy数组
print(x > 3)
x[x > 3]
Copy after login
[[False False False  True  True]]

array([5, 7])
Copy after login

第四部分 类型判别及类型转换

4.1 类型判别

  • type(变量)

age = 20
name = "Ada"
print(type(age))
print(type(name))
Copy after login
<class &#39;int&#39;>
<class &#39;str&#39;>
Copy after login
  • isinstance(变量,预判类型) 承认继承

  • 变量类型是预判类型的子类型,则为真,否则为假

print(isinstance(age, int))        # 承认继承 这里的int就相当于是一个类
Copy after login
True
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
print(isinstance(age, object))
print(isinstance(name, object))    # object 是所有类的老祖宗
Copy after login
True
True
Copy after login
  • 字符串检查方法

字符串.isdigit()字符是否只有数字组成

age = "20"
name = "Ada"
Copy after login
age.isdigit()
Copy after login
True
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
name.isdigit()
Copy after login
False
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

字符串.isalpha()字符是否只有字母组成

name.isalpha()
Copy after login
True
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
age.isalpha()
Copy after login
False
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

字符串.isalnum()字符是否只有数字和字母组成

"Ada20".isalnum()    # 比如可用于判断用户名是否合法
Copy after login
True
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

4.2 类型转换

  • 数字类型转字符串  str(数字类型)

age = 20
print("My age is "+str(age))
Copy after login
My age is 20
Copy after login
  • 仅有数字组成的字符串转数字  int()  float()  eval(232, 232, 232); background: rgb(249, 249, 249);">

    s1 = "20"
    s2 = "10.1"
    Copy after login
int(s1)     # 仅整型
# int(s2) 会错误
Copy after login
20
Copy after login
float(s1)
Copy after login
20.0
Copy after login
float(s2)
Copy after login
10.1
Copy after login
eval(232, 232, 232); background: rgb(249, 249, 249);">20
Copy after login
eval(232, 232, 232); background: rgb(249, 249, 249);">10.1
Copy after login

The above is the detailed content of What are the basic data types of Python and how to use them. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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