Mar 23, 2009

Python 内建类型,操作符,函数

 参见 Python Manual, Built-in Types


boolean False:
  • None
  • False
  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.
  • any empty sequence, for example, '', (), [].
  • any empty mapping, for example, {}.
  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. 
 逻辑操作

Operation Result
x or y if x is false, then y, else x
x and y if x is false, then x, else y
not x if x is false, then True, else False

比较操作
Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity

数值操作

Operation Result
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y,和 c 中含义相同 16/3=5
x // y (floored) quotient of x and y, equal to / when x and y are integers
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
long(x) x converted to long integer
float(x) x converted to floating point
complex(re,im) a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate() conjugate of the complex number c. (Identity on real numbers)
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
>>> 16 // 3
5
>>> 16 %3
1
>>> 16/3
5
>>> 16.0 /3
5.333333333333333
>>> 16.0//3
5.0
>>> 
Operation Result
math.trunc(x) x truncated to Integral
round(x[, n]) x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0.
math.floor(x) the greatest integral float <= x
math.ceil(x) the least integral float >= x

位操作
x | y bitwise or of x and y
x ^ y bitwise exclusive or of x and y
x & y bitwise and of x and y
x << n x shifted left by n bits
x >> n x shifted right by n bits
~x the bits of x inverted

序列类型 str, unicode, list, tuple, buffer, xrange
Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n, n * s n shallow copies of s concatenated
s[i] i‘th item of s, origin 0
s[i:j] slice of s from i to j, half open [i,j)
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s

str 的操作也是有必要熟悉的。

0 comments: