数据类型及运算
赋值
x = y = 123
a,b = 1,2
a,b = b,a
MAX_NUM = 100
内置类型
1.整型
2.浮点型3.14=314e-2
3.布尔型 :Ture、False
4.字符串型
运算
进制:0b、0o、0x 运算符:±*% /(浮点除) //(整除) **(幂)
divmod(13,4)
a += 2 a = a+2
类型转换
a = int('456')
b = int(True)
c = int(3.14)
int('abc')
int('true')
python整数大小无上限 类型转换不改变原有值,而是生成新值
round(value)
时间的表示
时间的元年是1970
import time
print(time.time())
比较运算符
==、!=…
逻辑运算符
or
>>> a = True
>>> b = False
>>> a or b
True
>>> 30 or b
30
>>> b or 30
30
and
>>> 30 and b
False
>>> b and a
False
>>> 30 and a
True
not
>>> not 1
False
>>> not False
True
同一运算符
is :判断是不是同一对象,比较的是地址 ==:比较的是值
>>> a = 1000
>>> b = 1000
>>> a == b
True
>>> a is b
False
>>> id(b)
2327959247312
>>> id(a)
2327959247568
整数缓存【-5,256】
>>> c = 3
>>> d = 3
>>> c is d
True
字符串
>>> ord('A')
65
>>> a = "I'm a student"
>>> b = 'I am "Tom"'
>>> c = """ name = "Tom" age = 1000"""
>>> d = ''
>>> e = ' '
>>> len(d)
0
>>> len(e)
1
>>> "aa" + "b"
'aab'
>>> "12"*5
'1212121212'
转义字符
/t /n
不换行打印
print("sxl", end='*')
print('ok')
取字符
a = input()
str('123')
>>> a = 'abcde'
>>> a[0]
'a'
>>> a[-1]
'e'
>>> a.replace('c','u')
'abude'
切片操作(包头不包尾)
>>> a = 'abcdefg'
>>> a [1:6:1]
'bcdef'
>>> a [:]
'abcdefg'
>>> a [1:]
'bcdefg'
>>> a [:2]
'ab'
>>> a [-4:-2]
'de'
>>> a [::-2]
'geca'
split()切割、join()合并
>>> a = 'to be or not to be'
>>> a.split()
['to', 'be', 'or', 'not', 'to', 'be']
>>> a.split('to')
['', ' be or not ', ' be']
>>> b = ['', ' be or not ', ' be']
>>> 'to'.join(b)
'to be or not to be'
import time
time01 = time.time()
a = ''
for i in range(100000):
a += 'sxl'
time02 = time.time()
print('join函数只生成一个对象的时间' + str(time02-time01))
time03 = time.time()
li = []
for i in range(100000):
li.append('sxl')
a = ''.join(li)
time04 = time.time()
print('+生成n个对象' + str(time04-time03))
字符串驻留机制
>>> a = 'abc_1'
>>> b = 'abc_1'
>>> id(a)
2590876081968
>>> id(b)
2590876081968
格式化str.format()
>>> a = '名字是{name},年龄是{age}'
>>> a.format(name ='sxl', age = 21)
'名字是sxl,年龄是21'
|