快速上手:基础知识
除法运算的结果为小数,即浮点数
>>>1/2
0.5
如果执行整除运算可以使用双斜杠
>>>1//2
0
内置函数round将浮点数圆整为与之最接近的整数,并在两个整数一样近时圆整到偶数。
>>>round(2/3)
1.0
math模块中的floor是求小于或等于给定数的最大整数。而ceil则返回大于或等于给定数的最小整数。
如果切丁不会从不同模块导入多个同名函数,在不想每次调用函数时都指定模块名,你可以使用以下命令:
>>>from math import sqrt
>>>sqrt(9)
3.0
负数的平方根为虚数,而由实部和虚部组成的数为复数。
>>>import cmath
>>>cmath.sqrt(-1)
1j
函数str能以合理的方式将值转为用户能够看懂的字符串
>>>print(str('Hello,\nworld!'))
Hello,
world!
函数repr会获得值合法Python表达式表示。
>>>print(repr('Hello,\nworld!'))
'Hello,\nworld!'
要表示很长的字符串(跨越多行的字符串),可以使用三引号
>>> print('''This is a very long string.It continues here.
... And it's not over yet."Hello,world!"
... Still here.''')
This is a very long string.It continues here.
And it's not over yet."Hello,world!"
Still here.
常规字符串也可以横跨多行。只要在行尾加上反斜杠,反斜杠和换行符将被转义。
>>> 1+2+\
... 4+5
12
原始字符串不以特殊方式处理反斜杠。原始字符串不能以单个反斜杠结尾。原始字符串用前缀r表示。
>>> print('C\nowhere')
C
owhere
>>> print(r'C:\nowhere')
C:\nowhere
Python字符串使用Unicode编码来表示文本。有一种指定Unicode字符的通用机制:使用16或32位的十六进制字面量(分别加上前缀\u或\U)或者使用字符的Unicode名称(\N{name}).
>>> "\u00C6"
'Æ'
>>> "\U0001F60A"
'?'
>>> "This is a cat:\N{cat}"
'This is a cat:?'