Python3 数字(Number)

定义:a=1

特性:

1.只能存放一个值

2.一经定义,不可更改

3.直接访问

分类:整型,长整型,布尔,浮点,复数

python2.*与python3.*关于整型的区别

  1. python2.* 32位机器上,整数的位数为32位,取值范围为-2**312**31-1,即-21474836482147483647
    64位系统上,整数的位数为64位,取值范围为-2**632**63-1,即-92233720368547758089223372036854775807 python3.*整形长度无限制

Python 数字数据类型用于存储数值。

数据类型是不允许改变的,这就意味着如果改变数字数据类型得值,将重新分配内存空间。

整型工厂函数int()

python2

  1. class int(object):
  2. """
  3. int(x=0) -> int or long
  4. int(x, base=10) -> int or long
  5.  
  6. Convert a number or string to an integer, or return 0 if no arguments
  7. are given. If x is floating point, the conversion truncates towards zero.
  8. If x is outside the integer range, the function returns a long instead.
  9.  
  10. If x is not a number or if base is given, then x must be a string or
  11. Unicode object representing an integer literal in the given base. The
  12. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  13. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
  14. interpret the base from the string as an integer literal.
  15. >>> int('0b100', base=0)
  16. """
  17. def bit_length(self):
  18. """ 返回表示该数字的时占用的最少位数 """
  19. """
  20. int.bit_length() -> int
  21.  
  22. Number of bits necessary to represent self in binary.
  23. >>> bin(37)
  24. '0b100101'
  25. >>> (37).bit_length()
  26. """
  27. return 0
  28.  
  29. def conjugate(self, *args, **kwargs): # real signature unknown
  30. """ 返回该复数的共轭复数 """
  31. """ Returns self, the complex conjugate of any int. """
  32. pass
  33.  
  34. def __abs__(self):
  35. """ 返回绝对值 """
  36. """ x.__abs__() <==> abs(x) """
  37. pass
  38.  
  39. def __add__(self, y):
  40. """ x.__add__(y) <==> x+y """
  41. pass
  42.  
  43. def __and__(self, y):
  44. """ x.__and__(y) <==> x&y """
  45. pass
  46.  
  47. def __cmp__(self, y):
  48. """ 比较两个数大小 """
  49. """ x.__cmp__(y) <==> cmp(x,y) """
  50. pass
  51.  
  52. def __coerce__(self, y):
  53. """ 强制生成一个元组 """
  54. """ x.__coerce__(y) <==> coerce(x, y) """
  55. pass
  56.  
  57. def __divmod__(self, y):
  58. """ 相除,得到商和余数组成的元组 """
  59. """ x.__divmod__(y) <==> divmod(x, y) """
  60. pass
  61.  
  62. def __div__(self, y):
  63. """ x.__div__(y) <==> x/y """
  64. pass
  65.  
  66. def __float__(self):
  67. """ 转换为浮点类型 """
  68. """ x.__float__() <==> float(x) """
  69. pass
  70.  
  71. def __floordiv__(self, y):
  72. """ x.__floordiv__(y) <==> x//y """
  73. pass
  74.  
  75. def __format__(self, *args, **kwargs): # real signature unknown
  76. pass
  77.  
  78. def __getattribute__(self, name):
  79. """ x.__getattribute__('name') <==> x.name """
  80. pass
  81.  
  82. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  83. """ 内部调用 __new__方法或创建对象时传入参数使用 """
  84. pass
  85.  
  86. def __hash__(self):
  87. """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
  88. """ x.__hash__() <==> hash(x) """
  89. pass
  90.  
  91. def __hex__(self):
  92. """ 返回当前数的 十六进制 表示 """
  93. """ x.__hex__() <==> hex(x) """
  94. pass
  95.  
  96. def __index__(self):
  97. """ 用于切片,数字无意义 """
  98. """ x[y:z] <==> x[y.__index__():z.__index__()] """
  99. pass
  100.  
  101. def __init__(self, x, base=10): # known special case of int.__init__
  102. """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
  103. """
  104. int(x=0) -> int or long
  105. int(x, base=10) -> int or long
  106.  
  107. Convert a number or string to an integer, or return 0 if no arguments
  108. are given. If x is floating point, the conversion truncates towards zero.
  109. If x is outside the integer range, the function returns a long instead.
  110.  
  111. If x is not a number or if base is given, then x must be a string or
  112. Unicode object representing an integer literal in the given base. The
  113. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  114. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
  115. interpret the base from the string as an integer literal.
  116. >>> int('0b100', base=0)
  117. # (copied from class doc)
  118. """
  119. pass
  120.  
  121. def __int__(self):
  122. """ 转换为整数 """
  123. """ x.__int__() <==> int(x) """
  124. pass
  125.  
  126. def __invert__(self):
  127. """ x.__invert__() <==> ~x """
  128. pass
  129.  
  130. def __long__(self):
  131. """ 转换为长整数 """
  132. """ x.__long__() <==> long(x) """
  133. pass
  134.  
  135. def __lshift__(self, y):
  136. """ x.__lshift__(y) <==> x<<y """
  137. pass
  138.  
  139. def __mod__(self, y):
  140. """ x.__mod__(y) <==> x%y """
  141. pass
  142.  
  143. def __mul__(self, y):
  144. """ x.__mul__(y) <==> x*y """
  145. pass
  146.  
  147. def __neg__(self):
  148. """ x.__neg__() <==> -x """
  149. pass
  150.  
  151. @staticmethod # known case of __new__
  152. def __new__(S, *more):
  153. """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
  154. pass
  155.  
  156. def __nonzero__(self):
  157. """ x.__nonzero__() <==> x != 0 """
  158. pass
  159.  
  160. def __oct__(self):
  161. """ 返回改值的 八进制 表示 """
  162. """ x.__oct__() <==> oct(x) """
  163. pass
  164.  
  165. def __or__(self, y):
  166. """ x.__or__(y) <==> x|y """
  167. pass
  168.  
  169. def __pos__(self):
  170. """ x.__pos__() <==> +x """
  171. pass
  172.  
  173. def __pow__(self, y, z=None):
  174. """ 幂,次方 """
  175. """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
  176. pass
  177.  
  178. def __radd__(self, y):
  179. """ x.__radd__(y) <==> y+x """
  180. pass
  181.  
  182. def __rand__(self, y):
  183. """ x.__rand__(y) <==> y&x """
  184. pass
  185.  
  186. def __rdivmod__(self, y):
  187. """ x.__rdivmod__(y) <==> divmod(y, x) """
  188. pass
  189.  
  190. def __rdiv__(self, y):
  191. """ x.__rdiv__(y) <==> y/x """
  192. pass
  193.  
  194. def __repr__(self):
  195. """转化为解释器可读取的形式 """
  196. """ x.__repr__() <==> repr(x) """
  197. pass
  198.  
  199. def __str__(self):
  200. """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
  201. """ x.__str__() <==> str(x) """
  202. pass
  203.  
  204. def __rfloordiv__(self, y):
  205. """ x.__rfloordiv__(y) <==> y//x """
  206. pass
  207.  
  208. def __rlshift__(self, y):
  209. """ x.__rlshift__(y) <==> y<<x """
  210. pass
  211.  
  212. def __rmod__(self, y):
  213. """ x.__rmod__(y) <==> y%x """
  214. pass
  215.  
  216. def __rmul__(self, y):
  217. """ x.__rmul__(y) <==> y*x """
  218. pass
  219.  
  220. def __ror__(self, y):
  221. """ x.__ror__(y) <==> y|x """
  222. pass
  223.  
  224. def __rpow__(self, x, z=None):
  225. """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
  226. pass
  227.  
  228. def __rrshift__(self, y):
  229. """ x.__rrshift__(y) <==> y>>x """
  230. pass
  231.  
  232. def __rshift__(self, y):
  233. """ x.__rshift__(y) <==> x>>y """
  234. pass
  235.  
  236. def __rsub__(self, y):
  237. """ x.__rsub__(y) <==> y-x """
  238. pass
  239.  
  240. def __rtruediv__(self, y):
  241. """ x.__rtruediv__(y) <==> y/x """
  242. pass
  243.  
  244. def __rxor__(self, y):
  245. """ x.__rxor__(y) <==> y^x """
  246. pass
  247.  
  248. def __sub__(self, y):
  249. """ x.__sub__(y) <==> x-y """
  250. pass
  251.  
  252. def __truediv__(self, y):
  253. """ x.__truediv__(y) <==> x/y """
  254. pass
  255.  
  256. def __trunc__(self, *args, **kwargs):
  257. """ 返回数值被截取为整形的值,在整形中无意义 """
  258. pass
  259.  
  260. def __xor__(self, y):
  261. """ x.__xor__(y) <==> x^y """
  262. pass
  263.  
  264. denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  265. """ 分母 = 1 """
  266. """the denominator of a rational number in lowest terms"""
  267.  
  268. imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  269. """ 虚数,无意义 """
  270. """the imaginary part of a complex number"""
  271.  
  272. numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  273. """ 分子 = 数字大小 """
  274. """the numerator of a rational number in lowest terms"""
  275.  
  276. real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  277. """ 实属,无意义 """
  278. """the real part of a complex number"""
  279.  
  280. int
  281.  
  282. python2.7

python3

  1. class int(object):
  2. """
  3. int(x=0) -> integer
  4. int(x, base=10) -> integer
  5.  
  6. Convert a number or string to an integer, or return 0 if no arguments
  7. are given. If x is a number, return x.__int__(). For floating point
  8. numbers, this truncates towards zero.
  9.  
  10. If x is not a number or if base is given, then x must be a string,
  11. bytes, or bytearray instance representing an integer literal in the
  12. given base. The literal can be preceded by '+' or '-' and be surrounded
  13. by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
  14. Base 0 means to interpret the base from the string as an integer literal.
  15. >>> int('0b100', base=0)
  16. """
  17. def bit_length(self): # real signature unknown; restored from __doc__
  18. """ 返回表示该数字的时占用的最少位数 """
  19. """
  20. int.bit_length() -> int
  21.  
  22. Number of bits necessary to represent self in binary.
  23. >>> bin(37)
  24. '0b100101'
  25. >>> (37).bit_length()
  26. """
  27. return 0
  28.  
  29. def conjugate(self, *args, **kwargs): # real signature unknown
  30. """ 返回该复数的共轭复数 """
  31. """ Returns self, the complex conjugate of any int. """
  32. pass
  33.  
  34. @classmethod # known case
  35. def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
  36. """
  37. int.from_bytes(bytes, byteorder, *, signed=False) -> int
  38.  
  39. Return the integer represented by the given array of bytes.
  40.  
  41. The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
  42.  
  43. The byteorder argument determines the byte order used to represent the
  44. integer. If byteorder is 'big', the most significant byte is at the
  45. beginning of the byte array. If byteorder is 'little', the most
  46. significant byte is at the end of the byte array. To request the native
  47. byte order of the host system, use `sys.byteorder' as the byte order value.
  48.  
  49. The signed keyword-only argument indicates whether two's complement is
  50. used to represent the integer.
  51. """
  52. pass
  53.  
  54. def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
  55. """
  56. int.to_bytes(length, byteorder, *, signed=False) -> bytes
  57.  
  58. Return an array of bytes representing an integer.
  59.  
  60. The integer is represented using length bytes. An OverflowError is
  61. raised if the integer is not representable with the given number of
  62. bytes.
  63.  
  64. The byteorder argument determines the byte order used to represent the
  65. integer. If byteorder is 'big', the most significant byte is at the
  66. beginning of the byte array. If byteorder is 'little', the most
  67. significant byte is at the end of the byte array. To request the native
  68. byte order of the host system, use `sys.byteorder' as the byte order value.
  69.  
  70. The signed keyword-only argument determines whether two's complement is
  71. used to represent the integer. If signed is False and a negative integer
  72. is given, an OverflowError is raised.
  73. """
  74. pass
  75.  
  76. def __abs__(self, *args, **kwargs): # real signature unknown
  77. """ abs(self) """
  78. pass
  79.  
  80. def __add__(self, *args, **kwargs): # real signature unknown
  81. """ Return self+value. """
  82. pass
  83.  
  84. def __and__(self, *args, **kwargs): # real signature unknown
  85. """ Return self&value. """
  86. pass
  87.  
  88. def __bool__(self, *args, **kwargs): # real signature unknown
  89. """ self != 0 """
  90. pass
  91.  
  92. def __ceil__(self, *args, **kwargs): # real signature unknown
  93. """
  94. 整数返回自己
  95. 如果是小数
  96. math.ceil(3.1)返回4
  97. """
  98. """ Ceiling of an Integral returns itself. """
  99. pass
  100.  
  101. def __divmod__(self, *args, **kwargs): # real signature unknown
  102. """ 相除,得到商和余数组成的元组 """
  103. """ Return divmod(self, value). """
  104. pass
  105.  
  106. def __eq__(self, *args, **kwargs): # real signature unknown
  107. """ Return self==value. """
  108. pass
  109.  
  110. def __float__(self, *args, **kwargs): # real signature unknown
  111. """ float(self) """
  112. pass
  113.  
  114. def __floordiv__(self, *args, **kwargs): # real signature unknown
  115. """ Return self//value. """
  116. pass
  117.  
  118. def __floor__(self, *args, **kwargs): # real signature unknown
  119. """ Flooring an Integral returns itself. """
  120. pass
  121.  
  122. def __format__(self, *args, **kwargs): # real signature unknown
  123. pass
  124.  
  125. def __getattribute__(self, *args, **kwargs): # real signature unknown
  126. """ Return getattr(self, name). """
  127. pass
  128.  
  129. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  130. pass
  131.  
  132. def __ge__(self, *args, **kwargs): # real signature unknown
  133. """ Return self>=value. """
  134. pass
  135.  
  136. def __gt__(self, *args, **kwargs): # real signature unknown
  137. """ Return self>value. """
  138. pass
  139.  
  140. def __hash__(self, *args, **kwargs): # real signature unknown
  141. """ Return hash(self). """
  142. pass
  143.  
  144. def __index__(self, *args, **kwargs): # real signature unknown
  145. """ 用于切片,数字无意义 """
  146. """ Return self converted to an integer, if self is suitable for use as an index into a list. """
  147. pass
  148.  
  149. def __init__(self, x, base=10): # known special case of int.__init__
  150. """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
  151. """
  152. int(x=0) -> integer
  153. int(x, base=10) -> integer
  154.  
  155. Convert a number or string to an integer, or return 0 if no arguments
  156. are given. If x is a number, return x.__int__(). For floating point
  157. numbers, this truncates towards zero.
  158.  
  159. If x is not a number or if base is given, then x must be a string,
  160. bytes, or bytearray instance representing an integer literal in the
  161. given base. The literal can be preceded by '+' or '-' and be surrounded
  162. by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
  163. Base 0 means to interpret the base from the string as an integer literal.
  164. >>> int('0b100', base=0)
  165. # (copied from class doc)
  166. """
  167. pass
  168.  
  169. def __int__(self, *args, **kwargs): # real signature unknown
  170.  
  171. """ int(self) """
  172. pass
  173.  
  174. def __invert__(self, *args, **kwargs): # real signature unknown
  175. """ ~self """
  176. pass
  177.  
  178. def __le__(self, *args, **kwargs): # real signature unknown
  179. """ Return self<=value. """
  180. pass
  181.  
  182. def __lshift__(self, *args, **kwargs): # real signature unknown
  183. """ Return self<<value. """
  184. pass
  185.  
  186. def __lt__(self, *args, **kwargs): # real signature unknown
  187. """ Return self<value. """
  188. pass
  189.  
  190. def __mod__(self, *args, **kwargs): # real signature unknown
  191. """ Return self%value. """
  192. pass
  193.  
  194. def __mul__(self, *args, **kwargs): # real signature unknown
  195. """ Return self*value. """
  196. pass
  197.  
  198. def __neg__(self, *args, **kwargs): # real signature unknown
  199. """ -self """
  200. pass
  201.  
  202. @staticmethod # known case of __new__
  203. def __new__(*args, **kwargs): # real signature unknown
  204. """ Create and return a new object. See help(type) for accurate signature. """
  205. pass
  206.  
  207. def __ne__(self, *args, **kwargs): # real signature unknown
  208. """ Return self!=value. """
  209. pass
  210.  
  211. def __or__(self, *args, **kwargs): # real signature unknown
  212. """ Return self|value. """
  213. pass
  214.  
  215. def __pos__(self, *args, **kwargs): # real signature unknown
  216. """ +self """
  217. pass
  218.  
  219. def __pow__(self, *args, **kwargs): # real signature unknown
  220. """ Return pow(self, value, mod). """
  221. pass
  222.  
  223. def __radd__(self, *args, **kwargs): # real signature unknown
  224. """ Return value+self. """
  225. pass
  226.  
  227. def __rand__(self, *args, **kwargs): # real signature unknown
  228. """ Return value&self. """
  229. pass
  230.  
  231. def __rdivmod__(self, *args, **kwargs): # real signature unknown
  232. """ Return divmod(value, self). """
  233. pass
  234.  
  235. def __repr__(self, *args, **kwargs): # real signature unknown
  236. """ Return repr(self). """
  237. pass
  238.  
  239. def __rfloordiv__(self, *args, **kwargs): # real signature unknown
  240. """ Return value//self. """
  241. pass
  242.  
  243. def __rlshift__(self, *args, **kwargs): # real signature unknown
  244. """ Return value<<self. """
  245. pass
  246.  
  247. def __rmod__(self, *args, **kwargs): # real signature unknown
  248. """ Return value%self. """
  249. pass
  250.  
  251. def __rmul__(self, *args, **kwargs): # real signature unknown
  252. """ Return value*self. """
  253. pass
  254.  
  255. def __ror__(self, *args, **kwargs): # real signature unknown
  256. """ Return value|self. """
  257. pass
  258.  
  259. def __round__(self, *args, **kwargs): # real signature unknown
  260. """
  261. Rounding an Integral returns itself.
  262. Rounding with an ndigits argument also returns an integer.
  263. """
  264. pass
  265.  
  266. def __rpow__(self, *args, **kwargs): # real signature unknown
  267. """ Return pow(value, self, mod). """
  268. pass
  269.  
  270. def __rrshift__(self, *args, **kwargs): # real signature unknown
  271. """ Return value>>self. """
  272. pass
  273.  
  274. def __rshift__(self, *args, **kwargs): # real signature unknown
  275. """ Return self>>value. """
  276. pass
  277.  
  278. def __rsub__(self, *args, **kwargs): # real signature unknown
  279. """ Return value-self. """
  280. pass
  281.  
  282. def __rtruediv__(self, *args, **kwargs): # real signature unknown
  283. """ Return value/self. """
  284. pass
  285.  
  286. def __rxor__(self, *args, **kwargs): # real signature unknown
  287. """ Return value^self. """
  288. pass
  289.  
  290. def __sizeof__(self, *args, **kwargs): # real signature unknown
  291. """ Returns size in memory, in bytes """
  292. pass
  293.  
  294. def __str__(self, *args, **kwargs): # real signature unknown
  295. """ Return str(self). """
  296. pass
  297.  
  298. def __sub__(self, *args, **kwargs): # real signature unknown
  299. """ Return self-value. """
  300. pass
  301.  
  302. def __truediv__(self, *args, **kwargs): # real signature unknown
  303. """ Return self/value. """
  304. pass
  305.  
  306. def __trunc__(self, *args, **kwargs): # real signature unknown
  307. """ Truncating an Integral returns itself. """
  308. pass
  309.  
  310. def __xor__(self, *args, **kwargs): # real signature unknown
  311. """ Return self^value. """
  312. pass
  313.  
  314. denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  315. """the denominator of a rational number in lowest terms"""
  316.  
  317. imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  318. """the imaginary part of a complex number"""
  319.  
  320. numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  321. """the numerator of a rational number in lowest terms"""
  322.  
  323. real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  324. """the real part of a complex number"""
  325.  
  326. python3.5

长整型long:

  1. python2.*: C语言不同,Python的长整型没有指定位宽,也就是说Python没有限制长整型数值的大小, 但是实际上由于机器内存有限,所以我们使用的长整型数值不可能无限大。 在使用过程中,我们如何区分长整型和整型数值呢? 通常的做法是在数字尾部加上一个大写字母L或小写字母l以表示该整数是长整型的,例如: a = 9223372036854775808L 注意,自从Python2起,如果发生溢出,Python会自动将整型数据转换为长整型, 所以如今在长整型数据后面不加字母L也不会导致严重后果了。
    python3.* 长整型,整型统一归为整型
  1. python2.7
  2. >>> a=9223372036854775807
  3. >>> a
  4. >>> a+=1
  5. >>> a
  6. 9223372036854775808L
  7.  
  8. python3.5
  9. >>> a=9223372036854775807
  10. >>> a
  11. >>> a+=1
  12. >>> a
  13. 9223372036854775808

以下实例在变量赋值时 Number 对象将被创建:

  1. var1 = 1
  2. var2 = 10

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647   
      在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
  1. class int(object):
  2. """
  3. int(x=0) -> int or long
  4. int(x, base=10) -> int or long
  5.  
  6. Convert a number or string to an integer, or return 0 if no arguments
  7. are given. If x is floating point, the conversion truncates towards zero.
  8. If x is outside the integer range, the function returns a long instead.
  9.  
  10. If x is not a number or if base is given, then x must be a string or
  11. Unicode object representing an integer literal in the given base. The
  12. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  13. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
  14. interpret the base from the string as an integer literal.
  15. >>> int('0b100', base=0)
  16. """
  17. def bit_length(self):
  18. """ 返回表示该数字的时占用的最少位数 """
  19. """
  20. int.bit_length() -> int
  21.  
  22. Number of bits necessary to represent self in binary.
  23. >>> bin(37)
  24. '0b100101'
  25. >>> (37).bit_length()
  26. """
  27. return 0
  28.  
  29. def conjugate(self, *args, **kwargs): # real signature unknown
  30. """ 返回该复数的共轭复数 """
  31. """ Returns self, the complex conjugate of any int. """
  32. pass
  33.  
  34. def __abs__(self):
  35. """ 返回绝对值 """
  36. """ x.__abs__() <==> abs(x) """
  37. pass
  38.  
  39. def __add__(self, y):
  40. """ x.__add__(y) <==> x+y """
  41. pass
  42.  
  43. def __and__(self, y):
  44. """ x.__and__(y) <==> x&y """
  45. pass
  46.  
  47. def __cmp__(self, y):
  48. """ 比较两个数大小 """
  49. """ x.__cmp__(y) <==> cmp(x,y) """
  50. pass
  51.  
  52. def __coerce__(self, y):
  53. """ 强制生成一个元组 """
  54. """ x.__coerce__(y) <==> coerce(x, y) """
  55. pass
  56.  
  57. def __divmod__(self, y):
  58. """ 相除,得到商和余数组成的元组 """
  59. """ x.__divmod__(y) <==> divmod(x, y) """
  60. pass
  61.  
  62. def __div__(self, y):
  63. """ x.__div__(y) <==> x/y """
  64. pass
  65.  
  66. def __float__(self):
  67. """ 转换为浮点类型 """
  68. """ x.__float__() <==> float(x) """
  69. pass
  70.  
  71. def __floordiv__(self, y):
  72. """ x.__floordiv__(y) <==> x//y """
  73. pass
  74.  
  75. def __format__(self, *args, **kwargs): # real signature unknown
  76. pass
  77.  
  78. def __getattribute__(self, name):
  79. """ x.__getattribute__('name') <==> x.name """
  80. pass
  81.  
  82. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  83. """ 内部调用 __new__方法或创建对象时传入参数使用 """
  84. pass
  85.  
  86. def __hash__(self):
  87. """如果对象object为哈希表类型,返回对象object的哈希值。哈希值为整数。在字典查找中,哈希值用于快速比较字典的键。两个数值如果相等,则哈希值也相等。"""
  88. """ x.__hash__() <==> hash(x) """
  89. pass
  90.  
  91. def __hex__(self):
  92. """ 返回当前数的 十六进制 表示 """
  93. """ x.__hex__() <==> hex(x) """
  94. pass
  95.  
  96. def __index__(self):
  97. """ 用于切片,数字无意义 """
  98. """ x[y:z] <==> x[y.__index__():z.__index__()] """
  99. pass
  100.  
  101. def __init__(self, x, base=10): # known special case of int.__init__
  102. """ 构造方法,执行 x = 123 或 x = int(10) 时,自动调用,暂时忽略 """
  103. """
  104. int(x=0) -> int or long
  105. int(x, base=10) -> int or long
  106.  
  107. Convert a number or string to an integer, or return 0 if no arguments
  108. are given. If x is floating point, the conversion truncates towards zero.
  109. If x is outside the integer range, the function returns a long instead.
  110.  
  111. If x is not a number or if base is given, then x must be a string or
  112. Unicode object representing an integer literal in the given base. The
  113. literal can be preceded by '+' or '-' and be surrounded by whitespace.
  114. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
  115. interpret the base from the string as an integer literal.
  116. >>> int('0b100', base=0)
  117. # (copied from class doc)
  118. """
  119. pass
  120.  
  121. def __int__(self):
  122. """ 转换为整数 """
  123. """ x.__int__() <==> int(x) """
  124. pass
  125.  
  126. def __invert__(self):
  127. """ x.__invert__() <==> ~x """
  128. pass
  129.  
  130. def __long__(self):
  131. """ 转换为长整数 """
  132. """ x.__long__() <==> long(x) """
  133. pass
  134.  
  135. def __lshift__(self, y):
  136. """ x.__lshift__(y) <==> x<<y """
  137. pass
  138.  
  139. def __mod__(self, y):
  140. """ x.__mod__(y) <==> x%y """
  141. pass
  142.  
  143. def __mul__(self, y):
  144. """ x.__mul__(y) <==> x*y """
  145. pass
  146.  
  147. def __neg__(self):
  148. """ x.__neg__() <==> -x """
  149. pass
  150.  
  151. @staticmethod # known case of __new__
  152. def __new__(S, *more):
  153. """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
  154. pass
  155.  
  156. def __nonzero__(self):
  157. """ x.__nonzero__() <==> x != 0 """
  158. pass
  159.  
  160. def __oct__(self):
  161. """ 返回改值的 八进制 表示 """
  162. """ x.__oct__() <==> oct(x) """
  163. pass
  164.  
  165. def __or__(self, y):
  166. """ x.__or__(y) <==> x|y """
  167. pass
  168.  
  169. def __pos__(self):
  170. """ x.__pos__() <==> +x """
  171. pass
  172.  
  173. def __pow__(self, y, z=None):
  174. """ 幂,次方 """
  175. """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """
  176. pass
  177.  
  178. def __radd__(self, y):
  179. """ x.__radd__(y) <==> y+x """
  180. pass
  181.  
  182. def __rand__(self, y):
  183. """ x.__rand__(y) <==> y&x """
  184. pass
  185.  
  186. def __rdivmod__(self, y):
  187. """ x.__rdivmod__(y) <==> divmod(y, x) """
  188. pass
  189.  
  190. def __rdiv__(self, y):
  191. """ x.__rdiv__(y) <==> y/x """
  192. pass
  193.  
  194. def __repr__(self):
  195. """转化为解释器可读取的形式 """
  196. """ x.__repr__() <==> repr(x) """
  197. pass
  198.  
  199. def __str__(self):
  200. """转换为人阅读的形式,如果没有适于人阅读的解释形式的话,则返回解释器课阅读的形式"""
  201. """ x.__str__() <==> str(x) """
  202. pass
  203.  
  204. def __rfloordiv__(self, y):
  205. """ x.__rfloordiv__(y) <==> y//x """
  206. pass
  207.  
  208. def __rlshift__(self, y):
  209. """ x.__rlshift__(y) <==> y<<x """
  210. pass
  211.  
  212. def __rmod__(self, y):
  213. """ x.__rmod__(y) <==> y%x """
  214. pass
  215.  
  216. def __rmul__(self, y):
  217. """ x.__rmul__(y) <==> y*x """
  218. pass
  219.  
  220. def __ror__(self, y):
  221. """ x.__ror__(y) <==> y|x """
  222. pass
  223.  
  224. def __rpow__(self, x, z=None):
  225. """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """
  226. pass
  227.  
  228. def __rrshift__(self, y):
  229. """ x.__rrshift__(y) <==> y>>x """
  230. pass
  231.  
  232. def __rshift__(self, y):
  233. """ x.__rshift__(y) <==> x>>y """
  234. pass
  235.  
  236. def __rsub__(self, y):
  237. """ x.__rsub__(y) <==> y-x """
  238. pass
  239.  
  240. def __rtruediv__(self, y):
  241. """ x.__rtruediv__(y) <==> y/x """
  242. pass
  243.  
  244. def __rxor__(self, y):
  245. """ x.__rxor__(y) <==> y^x """
  246. pass
  247.  
  248. def __sub__(self, y):
  249. """ x.__sub__(y) <==> x-y """
  250. pass
  251.  
  252. def __truediv__(self, y):
  253. """ x.__truediv__(y) <==> x/y """
  254. pass
  255.  
  256. def __trunc__(self, *args, **kwargs):
  257. """ 返回数值被截取为整形的值,在整形中无意义 """
  258. pass
  259.  
  260. def __xor__(self, y):
  261. """ x.__xor__(y) <==> x^y """
  262. pass
  263.  
  264. denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  265. """ 分母 = 1 """
  266. """the denominator of a rational number in lowest terms"""
  267.  
  268. imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  269. """ 虚数,无意义 """
  270. """the imaginary part of a complex number"""
  271.  
  272. numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  273. """ 分子 = 数字大小 """
  274. """the numerator of a rational number in lowest terms"""
  275.  
  276. real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  277. """ 实属,无意义 """
  278. """the real part of a complex number"""
  279.  
  280. int

您也可以使用del语句删除一些数字对象的引用。

del语句的语法是:

  1. del var1[,var2[,var3[....,varN]]]]

您可以通过使用del语句删除单个或多个对象的引用,例如:

  1. del var
  2. del var_a, var_b

Python 支持三种不同的数值类型:

  • 整型(Int) - 通常被称为是整型或整数,是正或负整数,不带小数点。Python3 整型是没有限制大小的,可以当作 Long 类型使用,所以 Python3 没有 Python2 的 Long 类型。
  • 浮点型(float) - 浮点型由整数部分与小数部分组成,浮点型也可以使用科学计数法表示(2.5e2 = 2.5 x 102 = 250)
  • 复数( (complex)) - 复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。

我们可以使用十六进制和八进制来代表整数:

  1. >>> number = 0xA0F # 十六进制
  2. >>> number
  3. 2575
  4.  
  5. >>> number=0o37 # 八进制
  6. >>> number
  7. 31
int float complex
10 0.0 3.14j
100 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
-0490 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j
  • Python支持复数,复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型。

Python 数字类型转换

有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。

  • int(x) 将x转换为一个整数。

  • float(x) 将x转换到一个浮点数。

  • complex(x) 将x转换到一个复数,实数部分为 x,虚数部分为 0。

  • complex(x, y) 将 x 和 y 转换到一个复数,实数部分为 x,虚数部分为 y。x 和 y 是数字表达式。

以下实例将浮点数变量 a 转换为整数:

  1. >>> a = 1.0
  2. >>> int(a)
  3. 1

Python 数字运算

Python 解释器可以作为一个简单的计算器,您可以在解释器里输入一个表达式,它将输出表达式的值。

表达式的语法很直白: +, -, * 和 / 和其它语言(如Pascal或C)里一样。例如:

  1. >>> 2 + 2
  2. 4
  3. >>> 50 - 5*6
  4. 20
  5. >>> (50 - 5*6) / 4
  6. 5.0
  7. >>> 8 / 5 # 总是返回一个浮点数
  8. 1.6

注意:在不同的机器上浮点运算的结果可能会不一样。

在整数除法中,除法(/)总是返回一个浮点数,如果只想得到整数的结果,丢弃可能的分数部分,可以使用运算符 //

  1. >>> 17 / 3 # 整数除法返回浮点型
  2. 5.666666666666667
  3. >>>
  4. >>> 17 // 3 # 整数除法返回向下取整后的结果
  5. 5
  6. >>> 17 % 3 # %操作符返回除法的余数
  7. 2
  8. >>> 5 * 3 + 2
  9. 17

等号(=)用于给变量赋值。赋值之后,除了下一个提示符,解释器不会显示任何结果。

  1. >>> width = 20
  2. >>> height = 5*9
  3. >>> width * height
  4. 900

Python 可以使用 ** 操作来进行幂运算:

  1. >>> 5 ** 2 # 5 的平方
  2. 25
  3. >>> 2 ** 7 # 2的7次方
  4. 128

变量在使用前必须先"定义"(即赋予变量一个值),否则会出现错误:

  1. >>> n # 尝试访问一个未定义的变量
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: name 'n' is not defined

不同类型的数混合运算时会将整数转换为浮点数:

  1. >>> 3 * 3.75 / 1.5
  2. 7.5
  3. >>> 7.0 / 2
  4. 3.5

在交互模式中,最后被输出的表达式结果被赋值给变量 _ 。例如:

  1. >>> tax = 12.5 / 100
  2. >>> price = 100.50
  3. >>> price * tax
  4. 12.5625
  5. >>> price + _
  6. 113.0625
  7. >>> round(_, 2)
  8. 113.06

此处, _ 变量应被用户视为只读变量。


数学函数

函数 返回值 ( 描述 )
abs(x) 返回数字的绝对值,如abs(-10) 返回 10
ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5

cmp(x, y)

如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 Python 3 已废弃 。使用 使用 (x>y)-(x<y) 替换。
exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
fabs(x) 返回数字的绝对值,如math.fabs(-10) 返回10.0
floor(x) 返回数字的下舍整数,如math.floor(4.9)返回 4
log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,...) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
round(x [,n]) 返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。
sqrt(x) 返回数字x的平方根,数字可以为负数,返回类型为实数,如math.sqrt(4)返回 2+0j

随机数函数

随机数可以用于数学,游戏,安全等领域中,还经常被嵌入到算法中,用以提高算法效率,并提高程序的安全性。

Python包含以下常用随机数函数:

函数 描述
choice(seq) 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。
randrange ([start,] stop [,step]) 从指定范围内,按指定基数递增的集合中获取一个随机数,基数缺省值为1
random() 随机生成下一个实数,它在[0,1)范围内。
seed([x]) 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。
shuffle(lst) 将序列的所有元素随机排序
uniform(x, y) 随机生成下一个实数,它在[x,y]范围内。

三角函数

Python包括以下三角函数:

函数 描述
acos(x) 返回x的反余弦弧度值。
asin(x) 返回x的反正弦弧度值。  
atan(x) 返回x的反正切弧度值。
atan2(y, x) 返回给定的 X 及 Y 坐标值的反正切值。
cos(x) 返回x的弧度的余弦值。
hypot(x, y) 返回欧几里德范数 sqrt(x*x + y*y)。
sin(x) 返回的x弧度的正弦值。
tan(x) 返回x弧度的正切值。
degrees(x) 将弧度转换为角度,如degrees(math.pi/2) ,  返回90.0
radians(x) 将角度转换为弧度

数学常量

常量 描述
pi 数学常量 pi(圆周率,一般以π来表示)
e 数学常量 e,e即自然常数(自然常数)。
布尔值
  真或假
  1 或 0

浮点数float:

  1. Python的浮点数就是数学中的小数,类似C语言中的double 在运算中,整数与浮点数运算的结果是浮点数 浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时, 一个浮点数的小数点位置是可变的,比如,1.23*10912.3*108是相等的。
    浮点数可以用数学写法,如1.233.14,-9.01,等等。但是对于很大或很小的浮点数, 就必须用科学计数法表示,把10e替代,1.23*109就是1.23e9,或者12.3e80.000012 可以写成1.2e-5,等等。 整数和浮点数在计算机内部存储的方式是不同的,
    整数运算永远是精确的而浮点数运算则可能会有 四舍五入的误差。

数字相关内建函数

 

Python3 字符串

字符串是 Python 中最常用的数据类型。我们可以使用引号('或")来创建字符串。

  1. 定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中间包含的内容称之为字符串 特性:
    1.只能存放一个值 2.不可变 3.按照从左到右的顺序定义字符集合,下标从0开始顺序访问,有序
    补充:   
    1.字符串的单引号和双引号都无法取消特殊字符的含义,如果想让引号内所有字符均取消特殊意义,在引号前面加r,如namer'l\thf'   
    2.unicode字符串与r连用必需在r前面,如nameur'l\thf'
字符串常用功能:
  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片
  1. class str(basestring):
  2. """
  3. str(object='') -> string
  4.  
  5. Return a nice string representation of the object.
  6. If the argument is a string, the return value is the same object.
  7. """
  8. def capitalize(self):
  9. """ 首字母变大写 """
  10. """
  11. S.capitalize() -> string
  12.  
  13. Return a copy of the string S with only its first character
  14. capitalized.
  15. """
  16. return ""
  17.  
  18. def center(self, width, fillchar=None):
  19. """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
  20. """
  21. S.center(width[, fillchar]) -> string
  22.  
  23. Return S centered in a string of length width. Padding is
  24. done using the specified fill character (default is a space)
  25. """
  26. return ""
  27.  
  28. def count(self, sub, start=None, end=None):
  29. """ 子序列个数 """
  30. """
  31. S.count(sub[, start[, end]]) -> int
  32.  
  33. Return the number of non-overlapping occurrences of substring sub in
  34. string S[start:end]. Optional arguments start and end are interpreted
  35. as in slice notation.
  36. """
  37. return 0
  38.  
  39. def decode(self, encoding=None, errors=None):
  40. """ 解码 """
  41. """
  42. S.decode([encoding[,errors]]) -> object
  43.  
  44. Decodes S using the codec registered for encoding. encoding defaults
  45. to the default encoding. errors may be given to set a different error
  46. handling scheme. Default is 'strict' meaning that encoding errors raise
  47. a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
  48. as well as any other name registered with codecs.register_error that is
  49. able to handle UnicodeDecodeErrors.
  50. """
  51. return object()
  52.  
  53. def encode(self, encoding=None, errors=None):
  54. """ 编码,针对unicode """
  55. """
  56. S.encode([encoding[,errors]]) -> object
  57.  
  58. Encodes S using the codec registered for encoding. encoding defaults
  59. to the default encoding. errors may be given to set a different error
  60. handling scheme. Default is 'strict' meaning that encoding errors raise
  61. a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  62. 'xmlcharrefreplace' as well as any other name registered with
  63. codecs.register_error that is able to handle UnicodeEncodeErrors.
  64. """
  65. return object()
  66.  
  67. def endswith(self, suffix, start=None, end=None):
  68. """ 是否以 xxx 结束 """
  69. """
  70. S.endswith(suffix[, start[, end]]) -> bool
  71.  
  72. Return True if S ends with the specified suffix, False otherwise.
  73. With optional start, test S beginning at that position.
  74. With optional end, stop comparing S at that position.
  75. suffix can also be a tuple of strings to try.
  76. """
  77. return False
  78.  
  79. def expandtabs(self, tabsize=None):
  80. """ 将tab转换成空格,默认一个tab转换成8个空格 """
  81. """
  82. S.expandtabs([tabsize]) -> string
  83.  
  84. Return a copy of S where all tab characters are expanded using spaces.
  85. If tabsize is not given, a tab size of 8 characters is assumed.
  86. """
  87. return ""
  88.  
  89. def find(self, sub, start=None, end=None):
  90. """ 寻找子序列位置,如果没找到,返回 -1 """
  91. """
  92. S.find(sub [,start [,end]]) -> int
  93.  
  94. Return the lowest index in S where substring sub is found,
  95. such that sub is contained within S[start:end]. Optional
  96. arguments start and end are interpreted as in slice notation.
  97.  
  98. Return -1 on failure.
  99. """
  100. return 0
  101.  
  102. def format(*args, **kwargs): # known special case of str.format
  103. """ 字符串格式化,动态参数,将函数式编程时细说 """
  104. """
  105. S.format(*args, **kwargs) -> string
  106.  
  107. Return a formatted version of S, using substitutions from args and kwargs.
  108. The substitutions are identified by braces ('{' and '}').
  109. """
  110. pass
  111.  
  112. def index(self, sub, start=None, end=None):
  113. """ 子序列位置,如果没找到,报错 """
  114. S.index(sub [,start [,end]]) -> int
  115.  
  116. Like S.find() but raise ValueError when the substring is not found.
  117. """
  118. return 0
  119.  
  120. def isalnum(self):
  121. """ 是否是字母和数字 """
  122. """
  123. S.isalnum() -> bool
  124.  
  125. Return True if all characters in S are alphanumeric
  126. and there is at least one character in S, False otherwise.
  127. """
  128. return False
  129.  
  130. def isalpha(self):
  131. """ 是否是字母 """
  132. """
  133. S.isalpha() -> bool
  134.  
  135. Return True if all characters in S are alphabetic
  136. and there is at least one character in S, False otherwise.
  137. """
  138. return False
  139.  
  140. def isdigit(self):
  141. """ 是否是数字 """
  142. """
  143. S.isdigit() -> bool
  144.  
  145. Return True if all characters in S are digits
  146. and there is at least one character in S, False otherwise.
  147. """
  148. return False
  149.  
  150. def islower(self):
  151. """ 是否小写 """
  152. """
  153. S.islower() -> bool
  154.  
  155. Return True if all cased characters in S are lowercase and there is
  156. at least one cased character in S, False otherwise.
  157. """
  158. return False
  159.  
  160. def isspace(self):
  161. """
  162. S.isspace() -> bool
  163.  
  164. Return True if all characters in S are whitespace
  165. and there is at least one character in S, False otherwise.
  166. """
  167. return False
  168.  
  169. def istitle(self):
  170. """
  171. S.istitle() -> bool
  172.  
  173. Return True if S is a titlecased string and there is at least one
  174. character in S, i.e. uppercase characters may only follow uncased
  175. characters and lowercase characters only cased ones. Return False
  176. otherwise.
  177. """
  178. return False
  179.  
  180. def isupper(self):
  181. """
  182. S.isupper() -> bool
  183.  
  184. Return True if all cased characters in S are uppercase and there is
  185. at least one cased character in S, False otherwise.
  186. """
  187. return False
  188.  
  189. def join(self, iterable):
  190. """ 连接 """
  191. """
  192. S.join(iterable) -> string
  193.  
  194. Return a string which is the concatenation of the strings in the
  195. iterable. The separator between elements is S.
  196. """
  197. return ""
  198.  
  199. def ljust(self, width, fillchar=None):
  200. """ 内容左对齐,右侧填充 """
  201. """
  202. S.ljust(width[, fillchar]) -> string
  203.  
  204. Return S left-justified in a string of length width. Padding is
  205. done using the specified fill character (default is a space).
  206. """
  207. return ""
  208.  
  209. def lower(self):
  210. """ 变小写 """
  211. """
  212. S.lower() -> string
  213.  
  214. Return a copy of the string S converted to lowercase.
  215. """
  216. return ""
  217.  
  218. def lstrip(self, chars=None):
  219. """ 移除左侧空白 """
  220. """
  221. S.lstrip([chars]) -> string or unicode
  222.  
  223. Return a copy of the string S with leading whitespace removed.
  224. If chars is given and not None, remove characters in chars instead.
  225. If chars is unicode, S will be converted to unicode before stripping
  226. """
  227. return ""
  228.  
  229. def partition(self, sep):
  230. """ 分割,前,中,后三部分 """
  231. """
  232. S.partition(sep) -> (head, sep, tail)
  233.  
  234. Search for the separator sep in S, and return the part before it,
  235. the separator itself, and the part after it. If the separator is not
  236. found, return S and two empty strings.
  237. """
  238. pass
  239.  
  240. def replace(self, old, new, count=None):
  241. """ 替换 """
  242. """
  243. S.replace(old, new[, count]) -> string
  244.  
  245. Return a copy of string S with all occurrences of substring
  246. old replaced by new. If the optional argument count is
  247. given, only the first count occurrences are replaced.
  248. """
  249. return ""
  250.  
  251. def rfind(self, sub, start=None, end=None):
  252. """
  253. S.rfind(sub [,start [,end]]) -> int
  254.  
  255. Return the highest index in S where substring sub is found,
  256. such that sub is contained within S[start:end]. Optional
  257. arguments start and end are interpreted as in slice notation.
  258.  
  259. Return -1 on failure.
  260. """
  261. return 0
  262.  
  263. def rindex(self, sub, start=None, end=None):
  264. """
  265. S.rindex(sub [,start [,end]]) -> int
  266.  
  267. Like S.rfind() but raise ValueError when the substring is not found.
  268. """
  269. return 0
  270.  
  271. def rjust(self, width, fillchar=None):
  272. """
  273. S.rjust(width[, fillchar]) -> string
  274.  
  275. Return S right-justified in a string of length width. Padding is
  276. done using the specified fill character (default is a space)
  277. """
  278. return ""
  279.  
  280. def rpartition(self, sep):
  281. """
  282. S.rpartition(sep) -> (head, sep, tail)
  283.  
  284. Search for the separator sep in S, starting at the end of S, and return
  285. the part before it, the separator itself, and the part after it. If the
  286. separator is not found, return two empty strings and S.
  287. """
  288. pass
  289.  
  290. def rsplit(self, sep=None, maxsplit=None):
  291. """
  292. S.rsplit([sep [,maxsplit]]) -> list of strings
  293.  
  294. Return a list of the words in the string S, using sep as the
  295. delimiter string, starting at the end of the string and working
  296. to the front. If maxsplit is given, at most maxsplit splits are
  297. done. If sep is not specified or is None, any whitespace string
  298. is a separator.
  299. """
  300. return []
  301.  
  302. def rstrip(self, chars=None):
  303. """
  304. S.rstrip([chars]) -> string or unicode
  305.  
  306. Return a copy of the string S with trailing whitespace removed.
  307. If chars is given and not None, remove characters in chars instead.
  308. If chars is unicode, S will be converted to unicode before stripping
  309. """
  310. return ""
  311.  
  312. def split(self, sep=None, maxsplit=None):
  313. """ 分割, maxsplit最多分割几次 """
  314. """
  315. S.split([sep [,maxsplit]]) -> list of strings
  316.  
  317. Return a list of the words in the string S, using sep as the
  318. delimiter string. If maxsplit is given, at most maxsplit
  319. splits are done. If sep is not specified or is None, any
  320. whitespace string is a separator and empty strings are removed
  321. from the result.
  322. """
  323. return []
  324.  
  325. def splitlines(self, keepends=False):
  326. """ 根据换行分割 """
  327. """
  328. S.splitlines(keepends=False) -> list of strings
  329.  
  330. Return a list of the lines in S, breaking at line boundaries.
  331. Line breaks are not included in the resulting list unless keepends
  332. is given and true.
  333. """
  334. return []
  335.  
  336. def startswith(self, prefix, start=None, end=None):
  337. """ 是否起始 """
  338. """
  339. S.startswith(prefix[, start[, end]]) -> bool
  340.  
  341. Return True if S starts with the specified prefix, False otherwise.
  342. With optional start, test S beginning at that position.
  343. With optional end, stop comparing S at that position.
  344. prefix can also be a tuple of strings to try.
  345. """
  346. return False
  347.  
  348. def strip(self, chars=None):
  349. """ 移除两段空白 """
  350. """
  351. S.strip([chars]) -> string or unicode
  352.  
  353. Return a copy of the string S with leading and trailing
  354. whitespace removed.
  355. If chars is given and not None, remove characters in chars instead.
  356. If chars is unicode, S will be converted to unicode before stripping
  357. """
  358. return ""
  359.  
  360. def swapcase(self):
  361. """ 大写变小写,小写变大写 """
  362. """
  363. S.swapcase() -> string
  364.  
  365. Return a copy of the string S with uppercase characters
  366. converted to lowercase and vice versa.
  367. """
  368. return ""
  369.  
  370. def title(self):
  371. """
  372. S.title() -> string
  373.  
  374. Return a titlecased version of S, i.e. words start with uppercase
  375. characters, all remaining cased characters have lowercase.
  376. """
  377. return ""
  378.  
  379. def translate(self, table, deletechars=None):
  380. """
  381. 转换,需要先做一个对应表,最后一个表示删除字符集合
  382. intab = "aeiou"
  383. outtab = "12345"
  384. trantab = maketrans(intab, outtab)
  385. str = "this is string example....wow!!!"
  386. print str.translate(trantab, 'xm')
  387. """
  388.  
  389. """
  390. S.translate(table [,deletechars]) -> string
  391.  
  392. Return a copy of the string S, where all characters occurring
  393. in the optional argument deletechars are removed, and the
  394. remaining characters have been mapped through the given
  395. translation table, which must be a string of length 256 or None.
  396. If the table argument is None, no translation is applied and
  397. the operation simply removes the characters in deletechars.
  398. """
  399. return ""
  400.  
  401. def upper(self):
  402. """
  403. S.upper() -> string
  404.  
  405. Return a copy of the string S converted to uppercase.
  406. """
  407. return ""
  408.  
  409. def zfill(self, width):
  410. """方法返回指定长度的字符串,原字符串右对齐,前面填充0"""
  411. """
  412. S.zfill(width) -> string
  413.  
  414. Pad a numeric string S with zeros on the left, to fill a field
  415. of the specified width. The string S is never truncated.
  416. """
  417. return ""
  418.  
  419. def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
  420. pass
  421.  
  422. def _formatter_parser(self, *args, **kwargs): # real signature unknown
  423. pass
  424.  
  425. def __add__(self, y):
  426. """ x.__add__(y) <==> x+y """
  427. pass
  428.  
  429. def __contains__(self, y):
  430. """ x.__contains__(y) <==> y in x """
  431. pass
  432.  
  433. def __eq__(self, y):
  434. """ x.__eq__(y) <==> x==y """
  435. pass
  436.  
  437. def __format__(self, format_spec):
  438. """
  439. S.__format__(format_spec) -> string
  440.  
  441. Return a formatted version of S as described by format_spec.
  442. """
  443. return ""
  444.  
  445. def __getattribute__(self, name):
  446. """ x.__getattribute__('name') <==> x.name """
  447. pass
  448.  
  449. def __getitem__(self, y):
  450. """ x.__getitem__(y) <==> x[y] """
  451. pass
  452.  
  453. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  454. pass
  455.  
  456. def __getslice__(self, i, j):
  457. """
  458. x.__getslice__(i, j) <==> x[i:j]
  459.  
  460. Use of negative indices is not supported.
  461. """
  462. pass
  463.  
  464. def __ge__(self, y):
  465. """ x.__ge__(y) <==> x>=y """
  466. pass
  467.  
  468. def __gt__(self, y):
  469. """ x.__gt__(y) <==> x>y """
  470. pass
  471.  
  472. def __hash__(self):
  473. """ x.__hash__() <==> hash(x) """
  474. pass
  475.  
  476. def __init__(self, string=''): # known special case of str.__init__
  477. """
  478. str(object='') -> string
  479.  
  480. Return a nice string representation of the object.
  481. If the argument is a string, the return value is the same object.
  482. # (copied from class doc)
  483. """
  484. pass
  485.  
  486. def __len__(self):
  487. """ x.__len__() <==> len(x) """
  488. pass
  489.  
  490. def __le__(self, y):
  491. """ x.__le__(y) <==> x<=y """
  492. pass
  493.  
  494. def __lt__(self, y):
  495. """ x.__lt__(y) <==> x<y """
  496. pass
  497.  
  498. def __mod__(self, y):
  499. """ x.__mod__(y) <==> x%y """
  500. pass
  501.  
  502. def __mul__(self, n):
  503. """ x.__mul__(n) <==> x*n """
  504. pass
  505.  
  506. @staticmethod # known case of __new__
  507. def __new__(S, *more):
  508. """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
  509. pass
  510.  
  511. def __ne__(self, y):
  512. """ x.__ne__(y) <==> x!=y """
  513. pass
  514.  
  515. def __repr__(self):
  516. """ x.__repr__() <==> repr(x) """
  517. pass
  518.  
  519. def __rmod__(self, y):
  520. """ x.__rmod__(y) <==> y%x """
  521. pass
  522.  
  523. def __rmul__(self, n):
  524. """ x.__rmul__(n) <==> n*x """
  525. pass
  526.  
  527. def __sizeof__(self):
  528. """ S.__sizeof__() -> size of S in memory, in bytes """
  529. pass
  530.  
  531. def __str__(self):
  532. """ x.__str__() <==> str(x) """
  533. pass
  534.  
  535. str
  1. num = "1" #unicode
  2. num.isdigit() # True
  3. num.isdecimal() # True
  4. num.isnumeric() # True
  5.  
  6. num = "1" # 全角
  7. num.isdigit() # True
  8. num.isdecimal() # True
  9. num.isnumeric() # True
  10.  
  11. num = b"1" # byte
  12. num.isdigit() # True
  13. num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
  14. num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
  15.  
  16. num = "IV" # 罗马数字
  17. num.isdigit() # True
  18. num.isdecimal() # False
  19. num.isnumeric() # True
  20.  
  21. num = "四" # 汉字
  22. num.isdigit() # False
  23. num.isdecimal() # False
  24. num.isnumeric() # True
  25.  
  26. ===================
  27. isdigit()
  28. True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
  29. False: 汉字数字
  30. Error:
  31.  
  32. isdecimal()
  33. True: Unicode数字,,全角数字(双字节)
  34. False: 罗马数字,汉字数字
  35. Error: byte数字(单字节)
  36.  
  37. isnumeric()
  38. True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
  39. False:
  40. Error: byte数字(单字节)
  41.  
  42. ================
  43. import unicodedata
  44.  
  45. unicodedata.digit("2") # 2
  46. unicodedata.decimal("2") # 2
  47. unicodedata.numeric("2") # 2.0
  48.  
  49. unicodedata.digit("2") # 2
  50. unicodedata.decimal("2") # 2
  51. unicodedata.numeric("2") # 2.0
  52.  
  53. unicodedata.digit(b"3") # TypeError: must be str, not bytes
  54. unicodedata.decimal(b"3") # TypeError: must be str, not bytes
  55. unicodedata.numeric(b"3") # TypeError: must be str, not bytes
  56.  
  57. unicodedata.digit("Ⅷ") # ValueError: not a digit
  58. unicodedata.decimal("Ⅷ") # ValueError: not a decimal
  59. unicodedata.numeric("Ⅷ") # 8.0
  60.  
  61. unicodedata.digit("四") # ValueError: not a digit
  62. unicodedata.decimal("四") # ValueError: not a decimal
  63. unicodedata.numeric("四") # 4.0
  64.  
  65. #"〇","零","一","壱","二","弐","三","参","四","五","六","七","八","九","十","廿","卅","卌","百","千","万","万","亿"
  66.  
  67. pythonstr函数isdigitisdecimalisnumeric的区别

创建字符串很简单,只要为变量分配一个值即可。例如:

  1. var1 = 'Hello World!'
  2. var2 = "Runoob"

Python 访问字符串中的值

Python 不支持单字符类型,单字符也在Python也是作为一个字符串使用。

Python 访问子字符串,可以使用方括号来截取字符串,如下实例:

  1. #!/usr/bin/python3
  2.  
  3. var1 = 'Hello World!'
  4. var2 = "Runoob"
  5.  
  6. print ("var1[0]: ", var1[0])
  7. print ("var2[1:5]: ", var2[1:5])

以上实例执行结果:

  1. var1[0]: H
  2. var2[1:5]: unoo

Python字符串更新

你可以对已存在的字符串进行修改,并赋值给另一个变量,如下实例:

  1. #!/usr/bin/python3
  2.  
  3. var1 = 'Hello World!'
  4.  
  5. print ("已更新字符串 : ", var1[:6] + 'Runoob!')

以上实例执行结果

  1. 已更新字符串 : Hello Runoob!

Python转义字符

在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表:

转义字符 描述
\(在行尾时) 续行符
\\ 反斜杠符号
\' 单引号
\" 双引号
\a 响铃
\b 退格(Backspace)
\e 转义
\000
\n 换行
\v 纵向制表符
\t 横向制表符
\r 回车
\f 换页
\oyy 八进制数,yy代表的字符,例如:\o12代表换行
\xyy 十六进制数,yy代表的字符,例如:\x0a代表换行
\other 其它的字符以普通格式输出

Python字符串运算符

下表实例变量a值为字符串 "Hello",b变量值为 "Python":

操作符 描述 实例
+ 字符串连接 a + b 输出结果: HelloPython
* 重复输出字符串 a*2 输出结果:HelloHello
[] 通过索引获取字符串中字符 a[1] 输出结果 e
[ : ] 截取字符串中的一部分 a[1:4] 输出结果 ell
in 成员运算符 - 如果字符串中包含给定的字符返回 True H in a 输出结果 1
not in 成员运算符 - 如果字符串中不包含给定的字符返回 True M not in a 输出结果 1
r/R 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。
原始字符串除在字符串的第一个引号前加上字母"r"(可以大小写)以外,与普通字符串有着几乎完全相同的语法。
print r'\n' prints \n 和 print R'\n' prints \n 
% 格式字符串 请看下一节内容。

实例

  1. #!/usr/bin/python3
  2.  
  3. a = "Hello"
  4. b = "Python"
  5.  
  6. print("a + b 输出结果:", a + b)
  7. print("a * 2 输出结果:", a * 2)
  8. print("a[1] 输出结果:", a[1])
  9. print("a[1:4] 输出结果:", a[1:4])
  10.  
  11. if( "H" in a) :
  12. print("H 在变量 a 中")
  13. else :
  14. print("H 不在变量 a 中")
  15.  
  16. if( "M" not in a) :
  17. print("M 不在变量 a 中")
  18. else :
  19. print("M 在变量 a 中")
  20.  
  21. print (r'\n')
  22. print (R'\n')

以上实例输出结果为:

  1. a + b 输出结果: HelloPython
  2. a * 2 输出结果: HelloHello
  3. a[1] 输出结果: e
  4. a[1:4] 输出结果: ell
  5. H 在变量 a
  6. M 不在变量 a
  7. \n
  8. \n

Python字符串格式化

Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。

在 Python 中,字符串格式化使用与 C 中 sprintf 函数一样的语法。

如下实例:

  1. #!/usr/bin/python3
  2.  
  3. print ("我叫 %s 今年 %d 岁!" % ('小明', 10))

以上实例输出结果:

  1. 我叫 小明 今年 10 岁!

python字符串格式化符号:

<tbody

    符   号 描述
      %c  格式化字符及其ASCII码
      %s  格式化字符串
      %d  格式化整数
      %u  格式化无符号整型
      %o  格式化无符号八进制数
      %x  格式化无符号十六进制数
      %X  格式化无符号十六进制数(大写)
      %f  格式化浮点数字,可指定小数点后的精度
      %e  用科学计数法格式化浮点数
      %E  作用同%e,用科学计数法格式化浮点数
      %g  %f和%e的简写
      %G  %f 和 %E 的简写
      %p  用十六进制数格式化变量的地址

格式化操作符辅助指令:

符号 功能
* 定义宽度或者小数点精度
- 用做左对齐
+ 在正数前面显示加号( + )
<sp> 在正数前面显示空格
# 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
0 显示的数字前面填充'0'而不是默认的空格
% '%%'输出一个单一的'%'
(var) 映射变量(字典参数)
m.n.   m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

Python三引号

python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。实例如下

  1. #!/usr/bin/python3
  2.  
  3. para_str = """这是一个多行字符串的实例
  4. 多行字符串可以使用制表符
  5. TAB ( \t )。
  6. 也可以使用换行符 [ \n ]。
  7. """
  8. print (para_str)

以上实例执行结果为:

  1. 这是一个多行字符串的实例
  2. 多行字符串可以使用制表符
  3. TAB ( )。
  4. 也可以使用换行符 [
  5. ]。

三引号让程序员从引号和特殊字符串的泥潭里面解脱出来,自始至终保持一小块字符串的格式是所谓的WYSIWYG(所见即所得)格式的。

一个典型的用例是,当你需要一块HTML或者SQL时,这时用字符串组合,特殊字符串转义将会非常的繁琐。

  1. errHTML = '''
  2. <HTML><HEAD><TITLE>
  3. Friends CGI Demo</TITLE></HEAD>
  4. <BODY><H3>ERROR</H3>
  5. <B>%s</B><P>
  6. <FORM><INPUT TYPE=button VALUE=Back
  7. ONCLICK="window.history.back()"></FORM>
  8. </BODY></HTML>
  9. '''
  10. cursor.execute('''
  11. CREATE TABLE users (
  12. login VARCHAR(8),
  13. uid INTEGER,
  14. prid INTEGER)
  15. ''')

Unicode 字符串

在Python2中,普通字符串是以8位ASCII码进行存储的,而Unicode字符串则存储为16位unicode字符串,这样能够表示更多的字符集。使用的语法是在字符串前面加上前缀 u

在Python3中,所有的字符串都是Unicode字符串。

小结

Python 3的字符串使用Unicode,直接支持多语言。

str和bytes互相转换时,需要指定编码。最常用的编码是UTF-8。Python当然也支持其他编码方式,比如把Unicode编码成GB2312:

  1. >>> '中文'.encode('gb2312')
  2. b'\xd6\xd0\xce\xc4'

但这种方式纯属自找麻烦,如果没有特殊业务要求,请牢记仅使用UTF-8编码。

格式化字符串的时候,可以用Python的交互式命令行测试,方便快捷。


Python 的字符串内建函数

Python 的字符串常用内建函数如下:

序号 方法及描述
1

capitalize() 将字符串的第一个字符转换为大写

2

center(width, fillchar)

返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。

3

count(str, beg= 0,end=len(string))

返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数

4

decode(encoding='UTF-8',errors='strict')

使用指定编码来解码字符串。默认编码为字符串编码。

5

encode(encoding='UTF-8',errors='strict')

以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'

6

endswith(suffix, beg=0, end=len(string)) 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.

7

expandtabs(tabsize=8)

把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。

8

find(str, beg=0 end=len(string))

检测 str 是否包含在字符串中 中,如果 beg 和 end 指定范围,则检查是否包含在指定范围内,如果是返回开始的索引值,否则返回-1

9

index(str, beg=0, end=len(string))

跟find()方法一样,只不过如果str不在字符串中会报一个异常.

10

isalnum()

如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False

11

isalpha()

如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False

12

isdigit()

如果字符串只包含数字则返回 True 否则返回 False..

13

islower()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False

14

isnumeric()

如果字符串中只包含数字字符,则返回 True,否则返回 False

15

isspace()

如果字符串中只包含空格,则返回 True,否则返回 False.

16

istitle()

如果字符串是标题化的(见 title())则返回 True,否则返回 False

17

isupper()

如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False

18

join(seq)

以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串

19

len(string)

返回字符串长度

20

ljust(width[, fillchar])

返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

21

lower()

转换字符串中所有大写字符为小写.

22

lstrip()

截掉字符串左边的空格

23

maketrans()

创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。

24

max(str)

返回字符串 str 中最大的字母。

25

min(str)

返回字符串 str 中最小的字母。

26

replace(old, new [, max])

把 将字符串中的 str1 替换成 str2,如果 max 指定,则替换不超过 max 次。

27

rfind(str, beg=0,end=len(string))

类似于 find()函数,不过是从右边开始查找.

28

rindex( str, beg=0, end=len(string))

类似于 index(),不过是从右边开始.

29

rjust(width,[, fillchar])

返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串

30

rstrip()

删除字符串字符串末尾的空格.

31

split(str="", num=string.count(str))

num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num 个子字符串

32

splitlines( num=string.count('\n'))

按照行分隔,返回一个包含各行作为元素的列表,如果 num 指定则仅切片 num 个行.

33

startswith(str, beg=0,end=len(string))

检查字符串是否是以 obj 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。

34

strip([chars])

在字符串上执行 lstrip()和 rstrip()

35

swapcase()

将字符串中大写转换为小写,小写转换为大写

36

title()

返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())

37

translate(table, deletechars="")

根据 str 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中

38

upper()

转换字符串中的小写字母为大写

39

zfill (width)

返回长度为 width 的字符串,原字符串右对齐,前面填充0

40

isdecimal()

检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。

Python3 列表

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

Python有6个序列的内置类型,但最常见的是列表和元组。

序列都可以进行的操作包括索引,切片,加,乘,检查成员。

此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。

列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。

Python内置的一种数据类型是列表:list。list是一种有序的集合,可以随时添加和删除其中的元素。

列表的数据项不需要具有相同的类型

  1. 定义:[]内以逗号分隔,按照索引,存放各种数据类型,每个位置代表一个元素
    特性:
    1.可存放多个值
    2.可修改指定索引位置对应的值,可变
    3.按照从左到右的顺序定义列表元素,下标从0开始顺序访问,有序

基本操作:

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 包含
  1. class list(object):
  2. """
  3. list() -> new empty list
  4. list(iterable) -> new list initialized from iterable's items
  5. """
  6. def append(self, p_object): # real signature unknown; restored from __doc__
  7. """ L.append(object) -- append object to end """
  8. pass
  9.  
  10. def count(self, value): # real signature unknown; restored from __doc__
  11. """ L.count(value) -> integer -- return number of occurrences of value """
  12. return 0
  13.  
  14. def extend(self, iterable): # real signature unknown; restored from __doc__
  15. """ L.extend(iterable) -- extend list by appending elements from the iterable """
  16. pass
  17.  
  18. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  19. """
  20. L.index(value, [start, [stop]]) -> integer -- return first index of value.
  21. Raises ValueError if the value is not present.
  22. """
  23. return 0
  24.  
  25. def insert(self, index, p_object): # real signature unknown; restored from __doc__
  26. """ L.insert(index, object) -- insert object before index """
  27. pass
  28.  
  29. def pop(self, index=None): # real signature unknown; restored from __doc__
  30. """
  31. L.pop([index]) -> item -- remove and return item at index (default last).
  32. Raises IndexError if list is empty or index is out of range.
  33. """
  34. pass
  35.  
  36. def remove(self, value): # real signature unknown; restored from __doc__
  37. """
  38. L.remove(value) -- remove first occurrence of value.
  39. Raises ValueError if the value is not present.
  40. """
  41. pass
  42.  
  43. def reverse(self): # real signature unknown; restored from __doc__
  44. """ L.reverse() -- reverse *IN PLACE* """
  45. pass
  46.  
  47. def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
  48. """
  49. L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
  50. cmp(x, y) -> -1, 0, 1
  51. """
  52. pass
  53.  
  54. def __add__(self, y): # real signature unknown; restored from __doc__
  55. """ x.__add__(y) <==> x+y """
  56. pass
  57.  
  58. def __contains__(self, y): # real signature unknown; restored from __doc__
  59. """ x.__contains__(y) <==> y in x """
  60. pass
  61.  
  62. def __delitem__(self, y): # real signature unknown; restored from __doc__
  63. """ x.__delitem__(y) <==> del x[y] """
  64. pass
  65.  
  66. def __delslice__(self, i, j): # real signature unknown; restored from __doc__
  67. """
  68. x.__delslice__(i, j) <==> del x[i:j]
  69.  
  70. Use of negative indices is not supported.
  71. """
  72. pass
  73.  
  74. def __eq__(self, y): # real signature unknown; restored from __doc__
  75. """ x.__eq__(y) <==> x==y """
  76. pass
  77.  
  78. def __getattribute__(self, name): # real signature unknown; restored from __doc__
  79. """ x.__getattribute__('name') <==> x.name """
  80. pass
  81.  
  82. def __getitem__(self, y): # real signature unknown; restored from __doc__
  83. """ x.__getitem__(y) <==> x[y] """
  84. pass
  85.  
  86. def __getslice__(self, i, j): # real signature unknown; restored from __doc__
  87. """
  88. x.__getslice__(i, j) <==> x[i:j]
  89.  
  90. Use of negative indices is not supported.
  91. """
  92. pass
  93.  
  94. def __ge__(self, y): # real signature unknown; restored from __doc__
  95. """ x.__ge__(y) <==> x>=y """
  96. pass
  97.  
  98. def __gt__(self, y): # real signature unknown; restored from __doc__
  99. """ x.__gt__(y) <==> x>y """
  100. pass
  101.  
  102. def __iadd__(self, y): # real signature unknown; restored from __doc__
  103. """ x.__iadd__(y) <==> x+=y """
  104. pass
  105.  
  106. def __imul__(self, y): # real signature unknown; restored from __doc__
  107. """ x.__imul__(y) <==> x*=y """
  108. pass
  109.  
  110. def __init__(self, seq=()): # known special case of list.__init__
  111. """
  112. list() -> new empty list
  113. list(iterable) -> new list initialized from iterable's items
  114. # (copied from class doc)
  115. """
  116. pass
  117.  
  118. def __iter__(self): # real signature unknown; restored from __doc__
  119. """ x.__iter__() <==> iter(x) """
  120. pass
  121.  
  122. def __len__(self): # real signature unknown; restored from __doc__
  123. """ x.__len__() <==> len(x) """
  124. pass
  125.  
  126. def __le__(self, y): # real signature unknown; restored from __doc__
  127. """ x.__le__(y) <==> x<=y """
  128. pass
  129.  
  130. def __lt__(self, y): # real signature unknown; restored from __doc__
  131. """ x.__lt__(y) <==> x<y """
  132. pass
  133.  
  134. def __mul__(self, n): # real signature unknown; restored from __doc__
  135. """ x.__mul__(n) <==> x*n """
  136. pass
  137.  
  138. @staticmethod # known case of __new__
  139. def __new__(S, *more): # real signature unknown; restored from __doc__
  140. """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
  141. pass
  142.  
  143. def __ne__(self, y): # real signature unknown; restored from __doc__
  144. """ x.__ne__(y) <==> x!=y """
  145. pass
  146.  
  147. def __repr__(self): # real signature unknown; restored from __doc__
  148. """ x.__repr__() <==> repr(x) """
  149. pass
  150.  
  151. def __reversed__(self): # real signature unknown; restored from __doc__
  152. """ L.__reversed__() -- return a reverse iterator over the list """
  153. pass
  154.  
  155. def __rmul__(self, n): # real signature unknown; restored from __doc__
  156. """ x.__rmul__(n) <==> n*x """
  157. pass
  158.  
  159. def __setitem__(self, i, y): # real signature unknown; restored from __doc__
  160. """ x.__setitem__(i, y) <==> x[i]=y """
  161. pass
  162.  
  163. def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
  164. """
  165. x.__setslice__(i, j, y) <==> x[i:j]=y
  166.  
  167. Use of negative indices is not supported.
  168. """
  169. pass
  170.  
  171. def __sizeof__(self): # real signature unknown; restored from __doc__
  172. """ L.__sizeof__() -- size of L in memory, in bytes """
  173. pass
  174.  
  175. __hash__ = None
  176.  
  177. list

创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:

  1. list1 = ['Google', 'Runoob', 1997, 2000];
  2. list2 = [1, 2, 3, 4, 5 ];
  3. list3 = ["a", "b", "c", "d"];

与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。

访问列表中的值

使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示:

  1. #!/usr/bin/python3
  2.  
  3. list1 = ['Google', 'Runoob', 1997, 2000];
  4. list2 = [1, 2, 3, 4, 5, 6, 7 ];
  5.  
  6. print ("list1[0]: ", list1[0])
  7. print ("list2[1:5]: ", list2[1:5])

以上实例输出结果:

  1. list1[0]: Google
  2. list2[1:5]: [2, 3, 4, 5]

更新列表

你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示:

  1. #!/usr/bin/python3
  2.  
  3. list = ['Google', 'Runoob', 1997, 2000]
  4.  
  5. print ("第三个元素为 : ", list[2])
  6. list[2] = 2001
  7. print ("更新后的第三个元素为 : ", list[2])

注意:我们会在接下来的章节讨论append()方法的使用

以上实例输出结果:

  1. 第三个元素为 : 1997
  2. 更新后的第三个元素为 : 2001

删除列表元素

可以使用 del 语句来删除列表的的元素,如下实例:

  1. #!/usr/bin/python3
  2.  
  3. list = ['Google', 'Runoob', 1997, 2000]
  4.  
  5. print (list)
  6. del list[2]
  7. print ("删除第三个元素 : ", list)

以上实例输出结果:

  1. 删除第三个元素 : ['Google', 'Runoob', 2000]

注意:我们会在接下来的章节讨论remove()方法的使用


Python列表脚本操作符

列表对 + 和  * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

如下所示:

Python 表达式 结果 描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合
['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 重复
3 in [1, 2, 3] True 元素是否存在于列表中
for x in [1, 2, 3]: print x, 1 2 3 迭代

Python列表截取与拼接

Python的列表截取与字符串操作类型,如下所示:

  1. L=['Google', 'Runoob', 'Taobao']

操作:

Python 表达式 结果 描述
L[2] 'Taobao' 读取第三个元素
L[-2] 'Runoob' 从右侧开始读取倒数第二个元素: count from the right
L[1:] ['Runoob', 'Taobao'] 输出从第二个元素开始后的所有元素
  1. >>> L=['Google', 'Runoob', 'Taobao']
  2. >>> L[2]
  3. 'Taobao'
  4. >>> L[-2]
  5. 'Runoob'
  6. >>> L[1:]
  7. ['Runoob', 'Taobao']
  8. >>>

列表还支持拼接操作:

  1. >>> squares = [1, 4, 9, 16, 25]
  2. >>> squares + [36, 49, 64, 81, 100]
  3. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

嵌套列表

使用嵌套列表即在列表里创建其它列表,例如:

  1. >>> a = ['a', 'b', 'c']
  2. >>> n = [1, 2, 3]
  3. >>> x = [a, n]
  4. >>> x
  5. [['a', 'b', 'c'], [1, 2, 3]]
  6. >>> x[0]
  7. ['a', 'b', 'c']
  8. >>> x[0][1]
  9. 'b'

Python列表函数&方法

Python包含以下函数:

序号 函数
1 len(list) 列表元素个数
2 max(list) 返回列表元素最大值
3 min(list) 返回列表元素最小值
4 list(seq) 将元组转换为列表

Python包含以下方法:

序号 方法
1 list.append(obj) 在列表末尾添加新的对象
2 list.count(obj) 统计某个元素在列表中出现的次数
3 list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj) 将对象插入列表
6 list.pop(obj=list[-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj) 移除列表中某个值的第一个匹配项
8 list.reverse() 反向列表中元素
9 list.sort([func]) 对原列表进行排序
10 list.clear() 清空列表
11 list.copy() 复制列表

python基础之数据类型(一)的更多相关文章

  1. Python基础之数据类型

    Python基础之数据类型 变量赋值 Python中的变量不需要声明,变量的赋值操作既是变量声明和定义的过程. 每个变量在内存中创建,都包括变量的标识,名称和数据这些信息. 每个变量在使用前都必须赋值 ...

  2. 第二章:python基础,数据类型

    """第二章:python基础,数据类型2.1 变量及身份运算补充2.2 二进制数2.3 字符编码每8位所占的空间位一个比特,这是计算机中最小的表示单位.每8个比特组成一 ...

  3. python基础一数据类型之字典

    摘要: python基础一数据类型之一字典,这篇主要讲字典. 1,定义字典 2,字典的基础知识 3,字典的方法 1,定义字典 1,定义1个空字典 dict1 = {} 2,定义字典 dict1 = d ...

  4. 第一节 Python基础之数据类型(整型,布尔值,字符串)

    数据类型是每一种语言的基础,就比如说一支笔,它的墨有可能是红色,有可能是黑色,也有可能是黄色等等,这不同的颜色就会被人用在不同的场景.Python中的数据类型也是一样,比如说我们要描述一个人的年龄:小 ...

  5. python基础一数据类型之集合

    摘要: python基础一中介绍数据类型的时候有集合,所以这篇主要讲集合. 1,集合的定义 2,集合的功能 3,集合的方法 1,集合的定义 list1 = [1,4,5,7,3,6,7,9] set1 ...

  6. python基础一数据类型之元祖

    摘要: python基础一中写到数据类型元祖,那么这篇主要讲元祖. 1,元祖定义 tuple1 = (1,2,'a','b') 元祖是不可变数据,所以又名只读列表.那么如何让是元祖可变呢?可以在元祖中 ...

  7. python基础一数据类型之列表

    摘要: python基础一中写到列表,那么这篇主要讲列表. 1,定义列表 2,列表.元祖.字符串都属于序列,都可以用用索引和切片. 3,列表的方法 1,定义列表 list1 = ['a','b',1, ...

  8. Python基础一数据类型之数字类型

    摘要: python基础一中提到了数据类型,这里主要讲解的是数字类型. 数字类型: 1,整型 2,长整型 3,浮点型 4,复数型 1,整型(int) 定义a = 1 通过type函数查看数据类型,整型 ...

  9. python基础(二)----数据类型

    Python基础第二章 二进制 字符编码 基本数据类型-数字 基本数据类型-字符串 基本数据类型-列表 基本数据类型-元组 可变.不可变数据类型和hash 基本数据类型-字典 基本数据类型-集合 二进 ...

  10. Python学习day04 - Python基础(2)数据类型基础

    <!doctype html>day04 - 博客 figure:last-child { margin-bottom: 0.5rem; } #write ol, #write ul { ...

随机推荐

  1. maven的聚合与继承

    新建一个空的maven项目user-parent Pom.xml内容 <project xmlns="http://maven.apache.org/POM/4.0.0" x ...

  2. MongoDB replica set IDs do not match

    在搭建MongoDB(版本 3.2.9)的Replica Set时,使用 rs.status() 查看Replica Set的状态,发现一个成员异常:replica set IDs do not ma ...

  3. python利用dict模拟switch

    pytho本身并未提供switch语句,但可以通过dict来模拟switch, #方法1 def add(x,y): return x+y def dec(x,y): return x-y def m ...

  4. 前端学PHP之字符串函数

    × 目录 [1]特点 [2]输出 [3]空格[4]大小写[5]HTML[6]格式化[7]比较 前面的话 字符串的处理和分析在任何编程语言中都是一个重要的基础,往往是简单而重要的.信息的分类.解析.存储 ...

  5. JAVA实现发送电子邮件

    相信大家对于网站也好,手机app也好,用户注册时,需要进行邮箱验证的功能特别好奇吧,本篇我将带领大家一起实现一下这个简单而又神奇的小功能,让我们的应用也可以加入这些神奇的元素.废话不多说,下面开始我们 ...

  6. 使用wireshark抓包分析浏览器无法建立WebSocket连接的问题(server为Alchemy WebSockets组件)

    工作时使用了Websocket技术,在使用的过程中发现,浏览器(Chrome)升级后可能会导致Websocket不可用,更换浏览器后可以正常使用. 近日偶尔一次在本地调试,发现使用相同版本的Chrom ...

  7. iOS开发之SQLite--C语言接口规范(五)——iOS开发使用SQLite实例

    本篇博客就使用前面操作SQLite的知识来实现如何去插入,删除和更新数据.然后再把操作SQlite数据库常用的方法进行一个封装.把常用方法进行封装后,把Cars数据库中的其中一个表的数据进行查询,并在 ...

  8. Java基本语法练习

    1.编写程序,求100以内的全部素数. 实验源码: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class F ...

  9. MySQL主从复制中断,报“Error on master: message (format)='Cannot delete or update a parent row: a foreign key constraint fails' error code=1217” 错误

    前几天,发现从库挂了,具体报错信息如下: 分析思路 1. 因为我采用的是选择性复制,只针对以下几个库进行复制: card,upay,deal,monitor,collect.所以,不太可能出现对于sa ...

  10. MySQL Range Optimization

    8.2.1.3 Range Optimization MYSQL的Range Optimization的目的还是尽可能的使用索引 The range access method uses a sing ...