三、python的基本类型
一、number
整数 int
浮点数 float
1、type()查看类型
>>> type(1) <class 'int'> >>> type(1.1) <class 'float'>
2、运算
+ 加
* 乘
/ 除,自动转float
// 整除,只保留整数部分
>>> 1+2 3 >>> 2*5 10 >>> 5/2 2.5 >>> 5//2 2
二、10、2、8、16进制
十进制:满十进一
二进制:满二进一
八进制
十六进制
三、各进制的表示与转换
1、表示
二进制:0b
八进制:0o
十六进制:0X
>>> 0b11 3 >>> 0o11 9 >>> 0x1F 31
2、转换
1)转十进制——回车/int()
2)转二进制——bin()
3)转八进制——oct()
3)转十六进制——hex()
>>> 0x1F 31 >>> bin(10) '0b1010' >>> int(0b1010) 10 >>> hex(888) '0x378' >>> oct(0b111) '0o7'
三、布尔类型与复数
bool布尔类型:真、假
complex:复数
1、bool类型
>>> True True >>> False False
注意:首字母必须大写
2、bool是number的一种
>>> int(True) 1 >>> int(False) 0
3、规律
None、0、‘’、[]、{}都会被认为是False
非零和非空都会被认为是True
>>> bool(1) True >>> bool(2.2) True >>> bool(0b111) True >>> bool(0b0) False >>> bool(0) False >>> bool('') False >>> bool([]) False >>> bool({}) False >>> bool(set()) False
六、单引号、双引号和三引号
1、表示str
单引号等价于双引号
>>> 'hello world' 'hello world' >>> "hello world" 'hello world'
字符串中间的引号如何表示?
1)成对出现,表示字符串是,引号须要成对出现
内单外双:
内双外单:
或\转义:
>>> "let's go" "let's go" >>> 'let"s go' 'let"s go' >>> 'les\'s go' "les's go"
2、多行字符串
python建议每行79个字符,那么如何表示多行字符串?
1)三引号表示多行字符串
>>> '''hello world ... hello world ... ''' 'hello world\nhello world\n' >>> """hello world ... hello world ... """ 'hello world\nhello world\n'
\n表示换行,那么如果输入\n,是否能表示换行动作?
>>> '''hello\n world\n''' 'hello\n world\n'
直接输入\n不能表示换行,需要使用print()函数
>>> print('''hello\nworld\n''') hello world
2)单、双引号表示换行
>>> 'hello\ ... world' 'helloworld' >>> "hello\ ... world" 'helloworld'
四、转义字符
特殊的字符,需要使用转义字符
1、无法“看见”的字符,如回车
2、与语言本身语法有冲突的字符,如单引号、双引号
\n——换行
\'——单引号
\t——横向制表符
\r——回车
>>> print('world\rhello') hello >>> print('world\thello') world hello >>> print('world\nhello') world hello
五、原始字符
print("hello \n world")要求\n也被输出显示
>>> print("hello \\n world") hello \n world
上例中将\ 当作2)类特殊字符,在其前面加上\即可实现需求
实际应用场景,打印某个文件路径
方法1)使用\
方法2)使用r或R,表示不是一个普通字符串,而是一个原始字符串
原始字符串:所见即所得,\不会被当做转义字符
>>> print('c\northwind\northwest') c orthwind orthwest >>> print('c\\northwind\\northwest') c\northwind\northwest >>> print(r'c\northwind\northwest') c\northwind\northwest >>> print(R'c\northwind\northwest') c\northwind\northwest
六、字符串的运算
1、拼接+
2、获取某个字符[n]
3、切片
>>> 'helle'+' '+'world' 'helle world' >>> 'hello '*3 'hello hello hello ' >>> 'hello world'[4] 'o' >>> 'hello world'[0:5] 'hello' >>> 'hello world'[0:-1] 'hello worl' >>> 'hello world'[0:-3] 'hello wo'
[:n]表示从头开始数n个
[-n:0]表示从末尾开始倒数n个
>>> 'hello world'[-3:] 'rld' >>> 'hello world'[:3] 'hel'