2.2:常用的Python数据类型、字符串、dtype

2023-02-15,,,,

一、内置数据类型

1、整型

2、浮点型

3、字符串

4、复数

5、布尔类型bool

6、None类型

二、字符串

1、从键盘输入数据

s = input()

2、用eval去引号求值

eval("5+3")

3、强制类型转换int("8")

4、强制类型转换str(5)

5、字符串连接--“+”

print("hello"+"world")

6、字符串复制--“*”

print("knock~"*2)

7、字符串判断

"H"  in "Hello"

8、字符串索引

s= "Hello Word"

s[1]

9、字符串切片

s="123456"

s[1:5:2],结果为"24"

10、字符串切割split

"192.168.0.1".split(".")

11、联合多个字符串join

":".join("192.168.0.1".split("."))

12、字符串替换replace

"192.168.0.1".replace(".",":")

13、字符串只读特性【不可变】

s = "hello"

s[0] ="H"

14、字符串截取

"abc 123#%".strip("# %")

三、dtype类型

1、认识dtype属性

import numpy as np

a= np.array([1,2,3,4])

a.dtype

结果输出:dtype('int32')

2、认识dtype()方法

type('i4')

type(np.dtype('i4'))

np.dtype('i4')

结果输出:<class ‘str’>、<class 'numpy.dtype'>和dtype('int32')

3、使用dtype()函数构造复杂类型

student = np.dtype([('name','S20'),  ('age',  'i1'),  ('marks',  'f4')])

student

type(student)

print(student)

结果输出:dtype([('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])

<class 'numpy.dtype'>

[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]

4、使用astype()方法

arr = np.arange(5)

arrarr.dtype

farr = arr.astype(np.float64)

farr.dtype

结果输出:arr输出array([0, 1, 2, 3, 4]),说明arr是一个包含了5个整数的数组。dtype('int32')说明arr里面的整数存放在4字节大小的类型空间中。farr.dtype输出结果是dtype('float64'),说明通过astype方法,将数据类型从int32修改为float64,原来的数组类型不变。

2.2常用的Python数据类型、字符串、dtype的相关教程结束。

《2.2:常用的Python数据类型、字符串、dtype.doc》

下载本文的Word格式文档,以方便收藏与打印。