python基础数据类型

整形:(不可变类型)

>>> a = 123
>>> type(a)
<class 'int'>

长整形:(在python3中已经废弃了)

>>> a = 123L
>>> type(a)
<type 'long'>

浮点型:

>>> c = 1.2
>>> type(c)
<class 'float'>

在python3和python2中,进行的运算之后的结果,首先默认会向参加运算的复杂类型靠拢

在python3中,除法的结果会自动向浮点数靠拢

>>> a = 1.0
>>> b = 5
>>> c = b / a
>>> type(c)
<class 'float'>

布尔型:

True :非0 、非空

False: 0

字符型:

>>> a = "xiaofan"
>>> type(a)
<class 'str'>

单引号和双引号用法上几乎是没有区别的,注意在多引号使用时的场景

>>> a = "It's a boy"

三引号:(输出的字符串是可以换行的)

>>> info = """my name is xiaofan
... I'm a boy """
>>> info
"my name is xiaofan\nI'm a boy "
>>> print(info)
my name is xiaofan
I'm a boy

转义:\ 或 r  (注意\不能再字符串的最后面出现)

>>> a = "\b"
>>> print(a)
>>> a = "\\b"
>>> print(a)
\b
>>> a = r"\b"
>>> print(a)
\b

索引的切片:

>>> name = "xiaofan"
>>> name[0]
'x'
>>> name[1]
'i'
>>> name[-1]
'n'
>>> name[0:4]
'xiao'

字符串是不可变类型 不能修改里面的值

name[1]=a

会报错

字符串拼接:

>>> name = "xiaofan"
>>> name + name
'xiaofanxiaofan'

字符串相乘:

>>> name * 3
'xiaofanxiaofanxiaofan'

列表:list

列表的索引:

>>> list1 = [1,2,3,['a',"b"],"c"]
>>> list1[0]
1
>>> list1[3][1]
'b'

>>> list1[3:5]
[['a', 'b'], 'c']
>>> list1[:]
[1, 2, 3, ['a', 'b'], 'c']

复杂列表取值:

list2=[1,2,3,4,5,6,7,8,[1,[3,[4,[5,[6,7,],7,],7,],8,],7,9],0,8]

如果取到其中的值:

>>> list2[-3]
[1, [3, [4, [5, [6, 7], 7], 7], 8], 7, 9]
>>> list2[-3][-3]
[3, [4, [5, [6, 7], 7], 7], 8]
>>> list2[-3][-3][-2]
[4, [5, [6, 7], 7], 7]
>>> list2[-3][-3][-2][-2]
[5, [6, 7], 7]
>>> list2[-3][-3][-2][-2][-2]
[6, 7]

修改列表的值:

>>> list1
[1, 2, 3, ['a', 'b'], 'c']
>>> list1[3][0]="xiaofan"
>>> list1
[1, 2, 3, ['xiaofan', 'b'], 'c']

修改列表内存地址不会改变:(列表是一个可变对象)

>>> list1=[1,2,3,4]
>>> id(list1)
140228069335304
>>> list1[1]="t"
>>> list1
[1, 't', 3, 4]
>>> id(list1)
140228069335304

python基础数据类型

元祖:tuple

>>> tuple1=(1,3,5,[1,3,6],"a",('a','b'))
>>> type(tuple1)
<class 'tuple'>
>>> tuple1[0]
1
>>> tuple1[-1]
('a', 'b')

元祖是不可以修改的(如果元祖里面有可变类型可以修改其中的内容)

>>> tuple1[3][0]='a'

元祖、列表转换:

>>> tuple1
(1, 3, 5, ['a', 3, 6], 'a', ('a', 'b'))

>>> list1=list(tuple1)
>>> list1
[1, 3, 5, ['a', 3, 6], 'a', ('a', 'b')]
>>> tuple(list1)
(1, 3, 5, ['a', 3, 6], 'a', ('a', 'b'))

del删除变量:

>>> list=1
>>> type(list)
<class 'int'>
>>> del list
>>> list
<class 'list'>

变量的引用计数:

>>> import sys
>>> num = 100
>>> sys.getrefcount(num)
7

引用计数为0时变量被删除

python基础数据类型

上一篇:你所不了解的float(滥用float的怪异现象)


下一篇:Java GC收集器配置说明