(1)Python3笔记 数据类型之Number与String
一、Number(数值)
1) 整数 : int
2) 浮点数: float
1 type(1) //int 2 type(1.0) // float 3 type(1+1) // int , 2 4 type(1+0.1) // float, 1.1 5 type(1+1.0) // float, 2.0 6 7 type(1*1) // int, 1 8 type(1*1.0) // float, 1.0 9 type(1/1) // float, 1.0 10 type(1//1) // int, 1 取整 11 type(1/2) // float, 0.5 12 type(1//2) // int, 0 取整
3) 复数(实际中很少用): complex: 36j, 1+2x
4) 布尔值(在Python2中bool不属于Number类型): bool [True, False]
1. int(True) == 1, int(False) == 0
2. bool(1) == True,bool(0) == False,bool(2) == True,bool(-1) == True,bool('') == False, bool([]) == False, bool(()) == False, bool({}) == False, bool(None) ==False
3. 总结:bool(非空值) == True, bool(空值或0或None) == False
5) 进制及转换:
二进制(0b**): 0b10==2, 0b11==3 ;方法: bin()
八进制(0o**):0o10==8, 0o11==9 ;方法:otc()
十进制:10==10, 9==9, 1==1 ;方法: int()
十六进制(0x**): 0x10==16, 0x11==17,0x1F==31 ;方法: fex()
二、String(字符串)
1) 表示方法(必须成对出现): 单引号(' hello '), 双引号(" hello "), 三引号(''' hello ''' 或 """ hello """)
1. 特殊情况 : "let's go" 内部的单引号为字符, 如外部使用单引号, 内部需使用双引号或者将单引号转义 ' let\'s go '
2. 三引号内字符串允许换行, 其他不允许换行
2) type(1) => int;type('1') => str
3) 特殊字符需转义(要将\转义则前面再加\, 即\\则输出一个\字符)
\n 换行
\' 单引号
\t 横向制表符
\r 回车
\ n
4)字符串操作
1. 字符串拼接(只有+和*) :
'hello ' + 'world' => 'hello world'
'hello' * 3 => 'hello hello hello'
2. 字符串切片:
1 'hello'[0] // 'h' 2 'hello'[3] // 'l' 3 'hello'[-1] // 'o' 4 'hello'[-4] // 'e' 5 'hello world'[0:4] // 'hell' 索引0开始,至索引4-1位置 6 'hello world'[0:-1] // 'hello wolr' 索引0开始, 除去倒数第1个 7 'hello world'[3:10] // 'lo worl' 索引3开始,至索引10-1位置 8 'hello wordl'[3:20] // 'lo world' 索引3开始, 至最后位置, 因为字符串长度不够20 9 10 11 'hello world'[3:] // 'lo world' 索引3开始至最后位置 12 'hello world'[:-3] // 'hello wo' 除去后三位 13 'hello world'[0:-3] // 同上 14 'hello world'[-3:] // 'orld' 从倒数第三位置截取到最后一位置
3. 原始字符串(特殊符号不用转义)
r' hello world ' ; r' let 's go ' ; r' C:\Windows'