第3章 理解什么是写代码与Python的基本类型
一、数字与布尔
1.1 Number:数字
int:整数
float:浮点数
代码示例:
python
type(1*1)
<class 'int'>
type(1*1.0)
<class 'float'>
type(2/2)
<class 'float'>
type(2//2)
<class 'int'>
1.2 进制的表示与转换
二进制:以0b开头
八进制:以0o开头
十六进制:以0x开头
python
0b10
2
0o10
8
0x10
16
其他进制转十进制:直接带前缀或者用int()方法
其他进制转二进制:bin()方法,对用单词binary
其他进制转八进制:oct()方法,对应单词octal
其他进制转十六进制:hex()方法,对应单词hexadecimal
1.3 bool布尔类型:表示真假
True False
不能是小写的true或false
python
bool(0)
False
bool(10101)
True
bool('')
False
bool('haha')
True
bool([])
False
bool([1,2])
True
bool({})
False
bool({1,2})
True
bool(None)
False
由上述代码得出,只要参数是空值,返回的就是False
1.4 complex:复数
后缀j:比如36j
二、字符串
2.1 单引号与双引号
python
>>> 'let"s go'
'let"s go'
>>> "let's go"
"let's go"
>>> 'let\'s go'
"let's go"
通过单双引号交替使用可以解决字符串中本身就有引号的问题,也可以使用转义字符,但不推荐。
2.2 多行字符串
python
>>> """
hello world
hello world
"""
'\nhello world\nhello world\n'
>>> """hello world
hello world"""
'hello world\nhello world'
>>> 'hello\
world'
'helloworld'
2.3 转义字符
2.4 原始字符串
在字符串前加r,表示原始字符串,不做转义,和双反斜一样
python
print('c:\\northwind\\northwest')
c:\northwind\northwest
print(r'c:\northwind\northwest')
c:\northwind\northwest
2.5 字符串运算
python
>>> 'hello wolrd'[1]
e
>>> 'hello world'[0:5]
hello
>>> 'hello world'[0:-1]
hello worl
python
>>> 'hello world'[6:30]
'world'
>>> 'hello world'[6:]
'world'
>>> 'hellow orld'[:-4]
'hellow '