1.内置函数
利用python内置函数
1). abs() #计算绝对值
2). 2**3 #幂运算
3). pow(2,3) #幂运算
4). round(3.4) #四舍五入取整
5). 2//3 #总是向下取整
2. 模块math
取整操作还可以在模块中完成
import math
math.floor(32.9) #向下取整
>>32
import math
math.ceil(32.4) #向上取整
>>33
开方运算
import math
math.sqrt(9) #向上取整
>>3
3. cmath和复数
import cmath
cmath.sqrt(-1)
>>1j
4. 字符串拼接
+号直接相加
"hello,"+'world'
>>'hello,world'
5. 字符串表示str和repr
str 能以合理的方式将值转换成用户能够看懂的字符串;
repr,通常会获得值的合法Python表达式表示。
\n 换行符
'Hello,\nworld'
>>'Hello,\nworld'
print("Hello,\nworld")
>>Hello,
world
————————————————————————————
以上另种分别等效于
print(repr("Hello,\nworld"))
>>'Hello,\nworld'
print(str("Hello,\nworld"))
>>Hello,
world
6. 长字符串、原始字符串和字节
1:长字符串,三引号'''
print('''this is a
long string,
it continues here.''')
>>this is a
long string,
it continues here.
2:原始字符串:加前缀r
指定 原始字符串时可以用单引号、双引号、三引号。
原始字符串不对反斜杠做特殊处理,让字符串包含的每个字符都保持原样。
print(r'C:\Program files\fold1\fold2')
>>C:\Program files\fold1\fold2
原始字符串不能以单个反斜杠结尾(最后一个字符串不能是反斜杠。)
print(r'C:\Program files\fold1\fold2\')
>>File "<ipython-input-25-ab16bf93ef4a>", line 1
print(r'C:\Program files\fold1\fold2\')
^
SyntaxError: EOL while scanning string literal
如果需要最后一个字符串是反斜杠,可以将反斜杠单独作为一个字符串,如下:
print(r'C:\Program files\fold1\fold2' '\\')
>>C:\Program files\fold1\fold2\