一、Python 运算符

1、算术运算:

2、比较运算:

3、赋值运算:

4、逻辑运算:

5、成员运算:

二、基本数据类型

1、数字整型

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807
 
  1. #返回表示该数字的时占用的最少位数
  2. >>> (951).bit_length()
  3. 10
  4.  
  5. #返回绝对值
  6. >>> (95).__abs__()
  7. 95
  8. >>> (-95).__abs__()
  9. 95
  10.  
  11. #用来区分数字和字符串的
  12. >>> (95).__add__(1)
  13. 96
  14. >>> (95).__add__("")
  15. NotImplemented
  16.  
  17. #判断一个整数对象是否为0,如果为0,则返回False,如果不为0,则返回True
  18. >>> (95).__bool__()
  19. True
  20. >>> (0).__bool__()
  21. False
  22.  
  23. #判断两个值是否相等
  24. >>> (95).__eq__(95)
  25. True
  26. >>> (95).__eq__(9)
  27. False
  28.  
  29. #判断是否不等于
  30. >>> (95).__ne__(9)
  31. True
  32. >>> (95).__ne__(95)
  33. False
  34.  
  35. #判断是否大于等于
  36. >>> (95).__ge__(9)
  37. True
  38. >>> (95).__ge__(99)
  39. False
  40.  
  41. #判断是否大于
  42. >>> (95).__gt__(9)
  43. True
  44. >>> (95).__gt__(99)
  45. False
  46.  
  47. #判断是否小于等于
  48. >>> (95).__le__(99)
  49. True
  50. >>> (95).__le__(9)
  51. False
  52.  
  53. #判断是否小于
  54. >>> (95).__lt__(9)
  55. False
  56. >>> (95).__lt__(99)
  57. True
  58.  
  59. #加法运算
  60. >>> (95).__add__(5)
  61. 100
  62.  
  63. #减法运算
  64. >>> (95).__sub__(5)
  65. 90
  66.  
  67. #乘法运算
  68. >>> (95).__mul__(10)
  69. 950
  70.  
  71. #除法运算
  72. >>> (95).__truediv__(5)
  73. 19.0
  74.  
  75. #取模运算
  76. >>> (95).__mod__(9)
  77. 5
  78.  
  79. #幂运算
  80. >>> (2).__pow__(10)
  81. 1024
  82.  
  83. #整除,保留结果的整数部分
  84. >>> (95).__floordiv__(9)
  85. >>>
  86.  
  87. #转换为整型
  88. >>> (9.5).__int__()
  89. 9
  90.  
  91. #返回一个对象的整数部分
  92. >>> (9.5).__trunc__()
  93. 9
  94.  
  95. #将正数变为负数,将负数变为正数
  96. >>> (95).__neg__()
  97. -95
  98. >>> (-95).__neg__()
  99. 95
  100.  
  101. #将一个正数转为字符串
  102. >>> a = 95
  103. >>> a = a.__str__()
  104. >>> print(type(a))
  105. <class 'str'>
  106.  
  107. #将一个整数转换成浮点型
  108. >>> (95).__float__()
  109. 95.0
  110.  
  111. #转换对象的类型
  112. >>> (95).__format__('f')
  113. '95.000000'
  114. >>> (95).__format__('b')
  115. ''
  116.  
  117. #在内存中占多少个字节
  118. >>> a = 95
  119. >>> a.__sizeof__()
  120. 28

int方法

  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. int.bit_length() -> int
  20.  
  21. Number of bits necessary to represent self in binary.
  22. """
  23. """
  24. 表示该数字返回时占用的最少位数
  25.  
  26. >>> (951).bit_length()
  27. 10
  28. """
  29. return 0
  30.  
  31. def conjugate(self, *args, **kwargs): # real signature unknown
  32. """ Returns self, the complex conjugate of any int."""
  33.  
  34. """
  35. 返回该复数的共轭复数
  36.  
  37. #返回复数的共轭复数
  38. >>> (95 + 11j).conjugate()
  39. (95-11j)
  40. #返回复数的实数部分
  41. >>> (95 + 11j).real
  42. 95.0
  43. #返回复数的虚数部分
  44. >>> (95 + 11j).imag
  45. 11.0
  46. """
  47. pass
  48.  
  49. @classmethod # known case
  50. def from_bytes(cls, bytes, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
  51. """
  52. int.from_bytes(bytes, byteorder, *, signed=False) -> int
  53.  
  54. Return the integer represented by the given array of bytes.
  55.  
  56. The bytes argument must be a bytes-like object (e.g. bytes or bytearray).
  57.  
  58. The byteorder argument determines the byte order used to represent the
  59. integer. If byteorder is 'big', the most significant byte is at the
  60. beginning of the byte array. If byteorder is 'little', the most
  61. significant byte is at the end of the byte array. To request the native
  62. byte order of the host system, use `sys.byteorder' as the byte order value.
  63.  
  64. The signed keyword-only argument indicates whether two's complement is
  65. used to represent the integer.
  66. """
  67. """
  68. 这个方法是在Python3.2的时候加入的,python官方给出了下面几个例子:
  69. >>> int.from_bytes(b'\x00\x10', byteorder='big')
  70. >>> int.from_bytes(b'\x00\x10', byteorder='little')
  71. >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)
  72. -1024
  73. >>> int.from_bytes(b'\xfc\x00', byteorder='big', signed=False)
  74. >>> int.from_bytes([255, 0, 0], byteorder='big')
  75. """
  76. pass
  77.  
  78. def to_bytes(self, length, byteorder, *args, **kwargs): # real signature unknown; NOTE: unreliably restored from __doc__
  79. """
  80. int.to_bytes(length, byteorder, *, signed=False) -> bytes
  81.  
  82. Return an array of bytes representing an integer.
  83.  
  84. The integer is represented using length bytes. An OverflowError is
  85. raised if the integer is not representable with the given number of
  86. bytes.
  87.  
  88. The byteorder argument determines the byte order used to represent the
  89. integer. If byteorder is 'big', the most significant byte is at the
  90. beginning of the byte array. If byteorder is 'little', the most
  91. significant byte is at the end of the byte array. To request the native
  92. byte order of the host system, use `sys.byteorder' as the byte order value.
  93.  
  94. The signed keyword-only argument determines whether two's complement is
  95. used to represent the integer. If signed is False and a negative integer
  96. is given, an OverflowError is raised.
  97. """
  98. """
  99. python官方给出了下面几个例子:
  100. >>> (1024).to_bytes(2, byteorder='big')
  101. b'\x04\x00'
  102. >>> (1024).to_bytes(10, byteorder='big')
  103. b'\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00'
  104. >>> (-1024).to_bytes(10, byteorder='big', signed=True)
  105. b'\xff\xff\xff\xff\xff\xff\xff\xff\xfc\x00'
  106. >>> x = 1000
  107. >>> x.to_bytes((x.bit_length() // 8) + 1, byteorder='little')
  108. b'\xe8\x03'
  109. """
  110. pass
  111.  
  112. def __abs__(self, *args, **kwargs): # real signature unknown
  113. """ abs(self)"""
  114.  
  115. """
  116. 返回一个绝对值
  117.  
  118. >>> (95).__abs__()
  119. -95
  120. >>> (-95).__abs__()
  121. 95
  122. """
  123. pass
  124.  
  125. def __add__(self, *args, **kwargs): # real signature unknown
  126. """ Return self+value."""
  127.  
  128. """
  129. 加法,也可区分数字和字符串
  130.  
  131. >>> (95).__add__(1)
  132. 96
  133. >>> (95).__add__("1")
  134. NotImplemented
  135. >>>
  136. """
  137. pass
  138.  
  139. def __and__(self, *args, **kwargs): # real signature unknown
  140. """ Return self&value."""
  141. pass
  142.  
  143. def __bool__(self, *args, **kwargs): # real signature unknown
  144. """ self != 0 """
  145.  
  146. """
  147. 判断一个整数对象是否为0,如果为0,则返回False,如果不为0,则返回True
  148.  
  149. >>> (95).__bool__()
  150. True
  151. >>> (0).__bool__()
  152. False
  153. """
  154. pass
  155.  
  156. def __ceil__(self, *args, **kwargs): # real signature unknown
  157. """ Ceiling of an Integral returns itself. """
  158. pass
  159.  
  160. def __divmod__(self, *args, **kwargs): # real signature unknown
  161. """ Return divmod(self, value). """
  162. """
  163. 返回一个元组,第一个元素为商,第二个元素为余数
  164.  
  165. >>> (9).__divmod__(5)
  166. (1, 4)
  167. """
  168. pass
  169.  
  170. def __eq__(self, *args, **kwargs): # real signature unknown
  171. """ Return self==value. """
  172. """
  173. 判断两个值是否相等
  174.  
  175. >>> (95).__eq__(95)
  176. True
  177. >>> (95).__eq__(9)
  178. False
  179. """
  180. pass
  181.  
  182. def __float__(self, *args, **kwargs): # real signature unknown
  183. """ float(self) """
  184. """
  185. 将一个整数转换成浮点型
  186.  
  187. >>> (95).__float__()
  188. 95.0
  189. """
  190. pass
  191.  
  192. def __floordiv__(self, *args, **kwargs): # real signature unknown
  193. """ Return self//value. """
  194. """
  195. 整除,保留结果的整数部分
  196.  
  197. >>> (95).__floordiv__(9)
  198. 10
  199. """
  200. pass
  201.  
  202. def __floor__(self, *args, **kwargs): # real signature unknown
  203. """ Flooring an Integral returns itself. """
  204. """
  205. 返回本身
  206.  
  207. >>> (95).__floor__()
  208. 95
  209. """
  210. pass
  211.  
  212. def __format__(self, *args, **kwargs): # real signature unknown
  213. """
  214. 转换对象的类型
  215.  
  216. >>> (95).__format__('f')
  217. '95.000000'
  218. >>> (95).__format__('b')
  219. '1011111'
  220. """
  221. pass
  222.  
  223. def __getattribute__(self, *args, **kwargs): # real signature unknown
  224. """ Return getattr(self, name). """
  225. """
  226. 判断这个类中是否包含这个属性,如果包含则打印出值,如果不包含,就报错了
  227.  
  228. >>> (95).__getattribute__('__abs__')
  229. <method-wrapper '__abs__' of int object at 0x9f93c0>
  230. >>> (95).__getattribute__('__aaa__')
  231. Traceback (most recent call last):
  232. File "<stdin>", line 1, in <module>
  233. AttributeError: 'int' object has no attribute '__aaa__'
  234. """
  235. pass
  236.  
  237. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  238. pass
  239.  
  240. def __ge__(self, *args, **kwargs): # real signature unknown
  241. """ Return self>=value. """
  242. """
  243. 判断是否大于等于
  244.  
  245. >>> (95).__ge__(9)
  246. True
  247. >>> (95).__ge__(99)
  248. False
  249. """
  250. pass
  251.  
  252. def __gt__(self, *args, **kwargs): # real signature unknown
  253. """ Return self>value. """
  254. """
  255. 判断是否大于
  256.  
  257. >>> (95).__gt__(9)
  258. True
  259. >>> (95).__gt__(99)
  260. False
  261. """
  262. pass
  263.  
  264. def __hash__(self, *args, **kwargs): # real signature unknown
  265. """ Return hash(self). """
  266. """
  267. 计算哈希值,整数返回本身
  268.  
  269. >>> (95).__hash__()
  270. 95
  271. >>> (95.95).__hash__()
  272. 2190550858753015903
  273. """
  274. pass
  275.  
  276. def __index__(self, *args, **kwargs): # real signature unknown
  277. """ Return self converted to an integer, if self is suitable for use as an index into a list. """
  278. pass
  279.  
  280. def __init__(self, x, base=10): # known special case of int.__init__
  281. """
  282. 这个是一个类的初始化方法,当int类被实例化的时候,这个方法默认就会被执行
  283. """
  284. """
  285. int(x=0) -> integer
  286. int(x, base=10) -> integer
  287.  
  288. Convert a number or string to an integer, or return 0 if no arguments
  289. are given. If x is a number, return x.__int__(). For floating point
  290. numbers, this truncates towards zero.
  291.  
  292. If x is not a number or if base is given, then x must be a string,
  293. bytes, or bytearray instance representing an integer literal in the
  294. given base. The literal can be preceded by '+' or '-' and be surrounded
  295. by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
  296. Base 0 means to interpret the base from the string as an integer literal.
  297. >>> int('0b100', base=0)
  298. # (copied from class doc)
  299. """
  300. pass
  301.  
  302. def __int__(self, *args, **kwargs): # real signature unknown
  303. """ int(self) """
  304. """
  305. 转换为整型
  306.  
  307. >>> (9.5).__int__()
  308. 9
  309. """
  310. pass
  311.  
  312. def __invert__(self, *args, **kwargs): # real signature unknown
  313. """ ~self """
  314.  
  315. pass
  316.  
  317. def __le__(self, *args, **kwargs): # real signature unknown
  318. """ Return self<=value. """
  319. """
  320. 判断是否小于等于
  321.  
  322. >>> (95).__le__(99)
  323. True
  324. >>> (95).__le__(9)
  325. False
  326. """
  327. pass
  328.  
  329. def __lshift__(self, *args, **kwargs): # real signature unknown
  330. """ Return self<<value. """
  331. """
  332. 用于二进制位移,这个是向左移动
  333.  
  334. >>> bin(95)
  335. '0b1011111'
  336. >>> a = (95).__lshift__(2)
  337. >>> bin(a)
  338. '0b101111100'
  339. >>>
  340. """
  341. pass
  342.  
  343. def __lt__(self, *args, **kwargs): # real signature unknown
  344. """ Return self<value. """
  345. """
  346. 判断是否小于
  347.  
  348. >>> (95).__lt__(9)
  349. False
  350. >>> (95).__lt__(99)
  351. True
  352. """
  353. pass
  354.  
  355. def __mod__(self, *args, **kwargs): # real signature unknown
  356. """ Return self%value. """
  357. """
  358. 取模 %
  359.  
  360. >>> (95).__mod__(9)
  361. """
  362. pass
  363.  
  364. def __mul__(self, *args, **kwargs): # real signature unknown
  365. """ Return self*value. """
  366. """
  367. 乘法 *
  368.  
  369. >>> (95).__mul__(10)
  370. """
  371. pass
  372.  
  373. def __neg__(self, *args, **kwargs): # real signature unknown
  374. """ -self """
  375. """
  376. 将正数变为负数,将负数变为正数
  377.  
  378. >>> (95).__neg__()
  379. -95
  380. >>> (-95).__neg__()
  381. 95
  382. """
  383. pass
  384.  
  385. @staticmethod # known case of __new__
  386. def __new__(*args, **kwargs): # real signature unknown
  387. """ Create and return a new object. See help(type) for accurate signature. """
  388. pass
  389.  
  390. def __ne__(self, *args, **kwargs): # real signature unknown
  391. """ Return self!=value. """
  392. """
  393. 不等于
  394.  
  395. >>> (95).__ne__(9)
  396. True
  397. >>> (95).__ne__(95)
  398. False
  399. """
  400. pass
  401.  
  402. def __or__(self, *args, **kwargs): # real signature unknown
  403. """ Return self|value. """
  404. """
  405. 二进制或的关系,只要有一个为真,就为真
  406.  
  407. >>> a = 4
  408. >>> b = 0
  409. >>> a.__or__(b) # a --> 00000100 b --> 00000000
  410. >>> b = 1 # b --> 00000001
  411. >>> a.__or__(b)
  412. """
  413. pass
  414.  
  415. def __pos__(self, *args, **kwargs): # real signature unknown
  416. """ +self """
  417. pass
  418.  
  419. def __pow__(self, *args, **kwargs): # real signature unknown
  420. """ Return pow(self, value, mod). """
  421. """
  422.  
  423. >>> (2).__pow__(10)
  424. 1024
  425. """
  426. pass
  427.  
  428. def __radd__(self, *args, **kwargs): # real signatre unknown
  429. """ Return value+self. """
  430. """
  431. 加法,将value放在前面
  432.  
  433. >>> a.__radd__(b) # 相当于 b+a
  434. """
  435. pass
  436.  
  437. def __rand__(self, *args, **kwargs): # real signature unknown
  438. """ Return value&self. """
  439. """
  440. 二进制与的关系,两个都为真,才为真,有一个为假,就为假
  441. """
  442. pass
  443.  
  444. def __rdivmod__(self, *args, **kwargs): # real signature unknown
  445. """ Return divmod(value, self). """
  446. pass
  447.  
  448. def __repr__(self, *args, **kwargs): # real signature unknown
  449. """ Return repr(self). """
  450. pass
  451.  
  452. def __rfloordiv__(self, *args, **kwargs): # real signature unknown
  453. """ Return value//self. """
  454. pass
  455.  
  456. def __rlshift__(self, *args, **kwargs): # real signature unknown
  457. """ Return value<<self. """
  458. pass
  459.  
  460. def __rmod__(self, *args, **kwargs): # real signature unknown
  461. """ Return value%self. """
  462. pass
  463.  
  464. def __rmul__(self, *args, **kwargs): # real signature unknown
  465. """ Return value*self. """
  466. pass
  467.  
  468. def __ror__(self, *args, **kwargs): # real signature unknown
  469. """ Return value|self. """
  470. pass
  471.  
  472. def __round__(self, *args, **kwargs): # real signature unknown
  473. """
  474. Rounding an Integral returns itself.
  475. Rounding with an ndigits argument also returns an integer.
  476. """
  477. pass
  478.  
  479. def __rpow__(self, *args, **kwargs): # real signature unknown
  480. """ Return pow(value, self, mod). """
  481. pass
  482.  
  483. def __rrshift__(self, *args, **kwargs): # real signature unknown
  484. """ Return value>>self. """
  485. pass
  486.  
  487. def __rshift__(self, *args, **kwargs): # real signature unknown
  488. """ Return self>>value. """
  489. pass
  490.  
  491. def __rsub__(self, *args, **kwargs): # real signature unknown
  492. """ Return value-self. """
  493. pass
  494.  
  495. def __rtruediv__(self, *args, **kwargs): # real signature unknown
  496. """ Return value/self. """
  497. pass
  498.  
  499. def __rxor__(self, *args, **kwargs): # real signature unknown
  500. """ Return value^self. """
  501. pass
  502.  
  503. def __sizeof__(self, *args, **kwargs): # real signature unknown
  504. """ Returns size in memory, in bytes """
  505. """
  506. 在内存中占多少个字节
  507.  
  508. >>> a = 95
  509. >>> a.__sizeof__()
  510. 28
  511. """
  512. pass
  513.  
  514. def __str__(self, *args, **kwargs): # real signature unknown
  515. """ Return str(self). """
  516. """
  517. 将一个正数转为字符串
  518.  
  519. >>> a = 95
  520. >>> a = a.__str__()
  521. >>> print(type(a))
  522. <class 'str'>
  523. """
  524. pass
  525.  
  526. def __sub__(self, *args, **kwargs): # real signature unknown
  527. """ Return self-value. """
  528. """
  529. 减法运算
  530.  
  531. >>> (95).__sub__(5)
  532. 90
  533. """
  534. pass
  535.  
  536. def __truediv__(self, *args, **kwargs): # real signature unknown
  537. """ Return self/value. """
  538. """
  539. 除法运算
  540.  
  541. >>> (95).__truediv__(5)
  542. 19.0
  543. """
  544. pass
  545.  
  546. def __trunc__(self, *args, **kwargs): # real signature unknown
  547. """ Truncating an Integral returns itself. """
  548. """
  549. 返回一个对象的整数部分
  550.  
  551. >>> (95.95).__trunc__()
  552. 95
  553. """
  554. pass
  555. def __xor__(self, *args, **kwargs): # real signature unknown
  556. """ Return self^value. """
  557. """
  558. 将对象与值进行二进制的或运算,一个为真,就为真
  559.  
  560. >>> a = 4
  561. >>> b = 1
  562. >>> a.__xor__(b)
  563. >>> c = 0
  564. >>> a.__xor__(c)
  565. """
  566.  
  567. pass
  568.  
  569. denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  570. """ 分母 = 1 """
  571. """the denominator of a rational number in lowest terms"""
  572.  
  573. imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  574. """ 虚数 """
  575. """the imaginary part of a complex number"""
  576.  
  577. numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  578. """ 分子 = 数字大小 """
  579. """the numerator of a rational number in lowest terms"""
  580.  
  581. real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
  582. """ 实属 """
  583. """the real part of a complex number"""

int

2、字符串

"hello  world"

str(字符串类型)

万恶的字符串拼接:

字符串一旦创建不可修改,一旦修改或者拼接,都会重新生成字符串

python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内存中重新开辟一块空间。
  1. #切片
  2.  
  3. #索引,从0号索引开始,获取字符串中的某一个字符
  4. string="allen中文"
  5. print(string[0])
  6.  
  7. #索引范围
  8. print(string[0:2])
  9.  
  10. #获取最后一个索引位置
  11. print(string[-1])
  12.  
  13. print(string[0:-1])
  14. #输出: alle
  15.  
  16. #len()获取字符串长度
  17. len(string)
  18. print("_".join(string))
  19.  
  20. #列子
  21. index=0
  22. while index<len(string):
  23. print(string[index])
  24. index+=1
  25.  
  26. #字符串替换
  27. new_string=string.replace('en','EN')
  28. print(new_string)
  29. #输出: allEN中文

切片

  1. #查看类型
  2. age=18
  3. my_name="obama"
  4.  
  5. print(type(age))
  6. print(type(my_name))
  7. #输出 :
  8. # <class 'int'>
  9. # <class 'str'>
  10.  
  11. #将字符串转换为整型
  12. number=""
  13. num= int(number)
  14. print(type(num),num)
  15.  
  16. #输出: <class 'int'> 123
  17.  
  18. #首字母转换为大写,其他字母都是小写
  19. name ='my name is AllEn'
  20. print(name.capitalize())
  21. # 输出:My name is allen
  22.  
  23. #所有字符转换为小写,比lower()更牛逼
  24. print(name.casefold())
  25. # 输出:my name is allen
  26.  
  27. #统计m出现次数
  28. print(name.count("m"))
  29. # 输出:2
  30.  
  31. #把name变量放在50个字符中间,设置宽度并把内容居中
  32. print(name.center(50,'-'))
  33. # 输出:-----------------my name is AllEn-----------------
  34.  
  35. #判断一个字符串是否以en结尾
  36. print(name.endswith('En'))
  37. # 输出:True
  38.  
  39. #判断一个字符串是否以my开始
  40. print(name.startswith('my'))
  41. # 输出:True
  42.  
  43. #查找子序列name,找到返回其索引,找不到返回-1
  44. print(name.find('name'))
  45.  
  46. # 输出:3
  47.  
  48. #字符串切片
  49. print(name[name.find('name'):])
  50. # 输出:name is AllEn
  51.  
  52. #format格式化用法1: 将字符串占位符替换为指定的值
  53. name_info='my name is {_name} and I am {_age} old'
  54. #
  55. #
  56. print(name_info.format(_name='allen',_age=18))
  57. # 输出:my name is allen and I am 18 old
  58.  
  59. #format格式化用法2:根据顺序替换
  60. name_info1='my name is {0} and I am {1} old'
  61.  
  62. print(name_info1.format('allen',18))
  63. # 输出:my name is allen and I am 18 old
  64.  
  65. #format_map 字典用法
  66. print(name_info.format_map({'_name':'allen','_age':20}))
  67. # 输出:my name is allen and I am 20 old
  68.  
  69. #查找索引,如果找不到会报错
  70. print(name.index('name'))
  71. # 输出:3
  72.  
  73. #判断是否包含数字和字母
  74. print('9aA'.isalnum())
  75. # 输出:True
  76.  
  77. #判断是否包含纯英文字符
  78. print('abA'.isalpha())
  79.  
  80. # 输出:True
  81.  
  82. # 判断是否是整数
  83. print(''.isdigit())
  84.  
  85. # 输出:True
  86.  
  87. #判断是否是数字,支持unicode
  88. test="二"
  89. print(test.isnumeric(),test)
  90. # 输出:True
  91.  
  92. #判断是不是合法的变量名
  93. print('1A'.isidentifier())
  94.  
  95. # 输出:False
  96.  
  97. #判断是否是小写
  98. print('abc'.islower())
  99. # 输出:True
  100.  
  101. #判断是否是大写
  102. print('33a'.isupper())
  103. # 输出:False
  104.  
  105. # 大小写互换
  106. print('AllEN'.swapcase())
  107. # 输出:aLLen
  108.  
  109. #字符串替换,只替换一次
  110. print('AlLeN'.replace('l','L',1))
  111. # 输出:ALLeN
  112.  
  113. #join连接两个字符串
  114. li = ["nick","serven"]
  115. a = "".join(li)
  116. b = "_".join(li)
  117. print(a)
  118. print(b)
  119.  
  120. #输出:nickserven
  121. # nick_serven
  122.  
  123. #大写变小写
  124. print('ALLen'.lower())
  125. # 输出:allen
  126.  
  127. # 小写变大写
  128. print('allen'.upper())
  129. # 输出:ALLEN
  130.  
  131. #去掉左右的空格(包括换行符和制表符)
  132. print(' all\ne\tn '.strip())
  133. # 输出:allen
  134.  
  135. #去掉左边空行和回车
  136. print(' allen '.lstrip())
  137. # 输出:allen
  138.  
  139. #去掉右边空行和回车
  140. print(' allen '.rstrip())
  141. # 输出: allen
  142.  
  143. #找到最右边目标的索引
  144. print('allenlaen'.rfind('a'))
  145. # 输出:6
  146.  
  147. #判断是否全部是空格
  148. test=" "
  149. print(test.isspace())
  150. # 输出:True
  151.  
  152. #判断是否是标题(首字母全部是大写)
  153. title="Return the highest index in S where substring sub"
  154. print(title.istitle(),title)
  155. # 输出:False
  156. # 转换为首字母全部为大写(转换为标题)
  157. print(title.title())
  158. # 输出:Return The Highest Index In S Where Substring Sub
  159.  
  160. #字符串切割 以t切分 t没有了
  161. print('allen test'.split('t'))
  162. # 输出:['allen ', 'es', '']
  163.  
  164. #字符串切割 以t切分,只分割一次
  165. print('allen test'.split('t',1))
  166. # 输出:['allen ', 'est']
  167.  
  168. #只根据换行符分割
  169. print("asdsad\nasdsad\nasda".splitlines())
  170.  
  171. #输出:['asdsad', 'asdsad', 'asda']
  172.  
  173. #表示长度50 不够右边*号填充
  174. print(name.ljust(50,'*'))
  175. # 输出:my name is AllEn**********************************
  176.  
  177. # 表示长度50 不够左边-号填充
  178. print(name.rjust(50,'-'))
  179. # 输出:----------------------------------my name is AllEn

str方法

  1. class str(object):
  2. """
  3. str(object='') -> str
  4. str(bytes_or_buffer[, encoding[, errors]]) -> str
  5.  
  6. Create a new string object from the given object. If encoding or
  7. errors is specified, then the object must expose a data buffer
  8. that will be decoded using the given encoding and error handler.
  9. Otherwise, returns the result of object.__str__() (if defined)
  10. or repr(object).
  11. encoding defaults to sys.getdefaultencoding().
  12. errors defaults to 'strict'.
  13. """
  14. def capitalize(self): # real signature unknown; restored from __doc__
  15. """
  16. S.capitalize() -> str
  17.  
  18. Return a capitalized version of S, i.e. make the first character
  19. have upper case and the rest lower case.
  20. """
  21. return ""
  22.  
  23. def casefold(self): # real signature unknown; restored from __doc__
  24. """
  25. S.casefold() -> str
  26.  
  27. Return a version of S suitable for caseless comparisons.
  28. """
  29. return ""
  30.  
  31. def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
  32. """
  33. S.center(width[, fillchar]) -> str
  34.  
  35. Return S centered in a string of length width. Padding is
  36. done using the specified fill character (default is a space)
  37. """
  38. return ""
  39.  
  40. def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  41. """
  42. S.count(sub[, start[, end]]) -> int
  43.  
  44. Return the number of non-overlapping occurrences of substring sub in
  45. string S[start:end]. Optional arguments start and end are
  46. interpreted as in slice notation.
  47. """
  48. return 0
  49.  
  50. def encode(self, encoding='utf-8', errors='strict'): # real signature unknown; restored from __doc__
  51. """
  52. S.encode(encoding='utf-8', errors='strict') -> bytes
  53.  
  54. Encode S using the codec registered for encoding. Default encoding
  55. is 'utf-8'. errors may be given to set a different error
  56. handling scheme. Default is 'strict' meaning that encoding errors raise
  57. a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
  58. 'xmlcharrefreplace' as well as any other name registered with
  59. codecs.register_error that can handle UnicodeEncodeErrors.
  60. """
  61. return b""
  62.  
  63. def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
  64. """
  65. S.endswith(suffix[, start[, end]]) -> bool
  66.  
  67. Return True if S ends with the specified suffix, False otherwise.
  68. With optional start, test S beginning at that position.
  69. With optional end, stop comparing S at that position.
  70. suffix can also be a tuple of strings to try.
  71. """
  72. return False
  73.  
  74. def expandtabs(self, tabsize=8): # real signature unknown; restored from __doc__
  75. """
  76. S.expandtabs(tabsize=8) -> str
  77.  
  78. Return a copy of S where all tab characters are expanded using spaces.
  79. If tabsize is not given, a tab size of 8 characters is assumed.
  80. """
  81. return ""
  82.  
  83. def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  84. """
  85. S.find(sub[, start[, end]]) -> int
  86.  
  87. Return the lowest index in S where substring sub is found,
  88. such that sub is contained within S[start:end]. Optional
  89. arguments start and end are interpreted as in slice notation.
  90.  
  91. Return -1 on failure.
  92. """
  93. return 0
  94.  
  95. def format(self, *args, **kwargs): # known special case of str.format
  96. """
  97. S.format(*args, **kwargs) -> str
  98.  
  99. Return a formatted version of S, using substitutions from args and kwargs.
  100. The substitutions are identified by braces ('{' and '}').
  101. """
  102. pass
  103.  
  104. def format_map(self, mapping): # real signature unknown; restored from __doc__
  105. """
  106. S.format_map(mapping) -> str
  107.  
  108. Return a formatted version of S, using substitutions from mapping.
  109. The substitutions are identified by braces ('{' and '}').
  110. """
  111. return ""
  112.  
  113. def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  114. """
  115. S.index(sub[, start[, end]]) -> int
  116.  
  117. Return the lowest index in S where substring sub is found,
  118. such that sub is contained within S[start:end]. Optional
  119. arguments start and end are interpreted as in slice notation.
  120.  
  121. Raises ValueError when the substring is not found.
  122. """
  123. return 0
  124.  
  125. def isalnum(self): # real signature unknown; restored from __doc__
  126. """
  127. S.isalnum() -> bool
  128.  
  129. Return True if all characters in S are alphanumeric
  130. and there is at least one character in S, False otherwise.
  131. """
  132. return False
  133.  
  134. def isalpha(self): # real signature unknown; restored from __doc__
  135. """
  136. S.isalpha() -> bool
  137.  
  138. Return True if all characters in S are alphabetic
  139. and there is at least one character in S, False otherwise.
  140. """
  141. return False
  142.  
  143. def isdecimal(self): # real signature unknown; restored from __doc__
  144. """
  145. S.isdecimal() -> bool
  146.  
  147. Return True if there are only decimal characters in S,
  148. False otherwise.
  149. """
  150. return False
  151.  
  152. def isdigit(self): # real signature unknown; restored from __doc__
  153. """
  154. S.isdigit() -> bool
  155.  
  156. Return True if all characters in S are digits
  157. and there is at least one character in S, False otherwise.
  158. """
  159. return False
  160.  
  161. def isidentifier(self): # real signature unknown; restored from __doc__
  162. """
  163. S.isidentifier() -> bool
  164.  
  165. Return True if S is a valid identifier according
  166. to the language definition.
  167.  
  168. Use keyword.iskeyword() to test for reserved identifiers
  169. such as "def" and "class".
  170. """
  171. return False
  172.  
  173. def islower(self): # real signature unknown; restored from __doc__
  174. """
  175. S.islower() -> bool
  176.  
  177. Return True if all cased characters in S are lowercase and there is
  178. at least one cased character in S, False otherwise.
  179. """
  180. return False
  181.  
  182. def isnumeric(self): # real signature unknown; restored from __doc__
  183. """
  184. S.isnumeric() -> bool
  185.  
  186. Return True if there are only numeric characters in S,
  187. False otherwise.
  188. """
  189. return False
  190.  
  191. def isprintable(self): # real signature unknown; restored from __doc__
  192. """
  193. S.isprintable() -> bool
  194.  
  195. Return True if all characters in S are considered
  196. printable in repr() or S is empty, False otherwise.
  197. """
  198. return False
  199.  
  200. def isspace(self): # real signature unknown; restored from __doc__
  201. """
  202. S.isspace() -> bool
  203.  
  204. Return True if all characters in S are whitespace
  205. and there is at least one character in S, False otherwise.
  206. """
  207. return False
  208.  
  209. def istitle(self): # real signature unknown; restored from __doc__
  210. """
  211. S.istitle() -> bool
  212.  
  213. Return True if S is a titlecased string and there is at least one
  214. character in S, i.e. upper- and titlecase characters may only
  215. follow uncased characters and lowercase characters only cased ones.
  216. Return False otherwise.
  217. """
  218. return False
  219.  
  220. def isupper(self): # real signature unknown; restored from __doc__
  221. """
  222. S.isupper() -> bool
  223.  
  224. Return True if all cased characters in S are uppercase and there is
  225. at least one cased character in S, False otherwise.
  226. """
  227. return False
  228.  
  229. def join(self, iterable): # real signature unknown; restored from __doc__
  230. """
  231. S.join(iterable) -> str
  232.  
  233. Return a string which is the concatenation of the strings in the
  234. iterable. The separator between elements is S.
  235. """
  236. return ""
  237.  
  238. def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
  239. """
  240. S.ljust(width[, fillchar]) -> str
  241.  
  242. Return S left-justified in a Unicode string of length width. Padding is
  243. done using the specified fill character (default is a space).
  244. """
  245. return ""
  246.  
  247. def lower(self): # real signature unknown; restored from __doc__
  248. """
  249. S.lower() -> str
  250.  
  251. Return a copy of the string S converted to lowercase.
  252. """
  253. return ""
  254.  
  255. def lstrip(self, chars=None): # real signature unknown; restored from __doc__
  256. """
  257. S.lstrip([chars]) -> str
  258.  
  259. Return a copy of the string S with leading whitespace removed.
  260. If chars is given and not None, remove characters in chars instead.
  261. """
  262. return ""
  263.  
  264. def maketrans(self, *args, **kwargs): # real signature unknown
  265. """
  266. Return a translation table usable for str.translate().
  267.  
  268. If there is only one argument, it must be a dictionary mapping Unicode
  269. ordinals (integers) or characters to Unicode ordinals, strings or None.
  270. Character keys will be then converted to ordinals.
  271. If there are two arguments, they must be strings of equal length, and
  272. in the resulting dictionary, each character in x will be mapped to the
  273. character at the same position in y. If there is a third argument, it
  274. must be a string, whose characters will be mapped to None in the result.
  275. """
  276. pass
  277.  
  278. def partition(self, sep): # real signature unknown; restored from __doc__
  279. """
  280. S.partition(sep) -> (head, sep, tail)
  281.  
  282. Search for the separator sep in S, and return the part before it,
  283. the separator itself, and the part after it. If the separator is not
  284. found, return S and two empty strings.
  285. """
  286. pass
  287.  
  288. def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
  289. """
  290. S.replace(old, new[, count]) -> str
  291.  
  292. Return a copy of S with all occurrences of substring
  293. old replaced by new. If the optional argument count is
  294. given, only the first count occurrences are replaced.
  295. """
  296. return ""
  297.  
  298. def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  299. """
  300. S.rfind(sub[, start[, end]]) -> int
  301.  
  302. Return the highest index in S where substring sub is found,
  303. such that sub is contained within S[start:end]. Optional
  304. arguments start and end are interpreted as in slice notation.
  305.  
  306. Return -1 on failure.
  307. """
  308. return 0
  309.  
  310. def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
  311. """
  312. S.rindex(sub[, start[, end]]) -> int
  313.  
  314. Return the highest index in S where substring sub is found,
  315. such that sub is contained within S[start:end]. Optional
  316. arguments start and end are interpreted as in slice notation.
  317.  
  318. Raises ValueError when the substring is not found.
  319. """
  320. return 0
  321.  
  322. def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__
  323. """
  324. S.rjust(width[, fillchar]) -> str
  325.  
  326. Return S right-justified in a string of length width. Padding is
  327. done using the specified fill character (default is a space).
  328. """
  329. return ""
  330.  
  331. def rpartition(self, sep): # real signature unknown; restored from __doc__
  332. """
  333. S.rpartition(sep) -> (head, sep, tail)
  334.  
  335. Search for the separator sep in S, starting at the end of S, and return
  336. the part before it, the separator itself, and the part after it. If the
  337. separator is not found, return two empty strings and S.
  338. """
  339. pass
  340.  
  341. def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
  342. """
  343. S.rsplit(sep=None, maxsplit=-1) -> list of strings
  344.  
  345. Return a list of the words in S, using sep as the
  346. delimiter string, starting at the end of the string and
  347. working to the front. If maxsplit is given, at most maxsplit
  348. splits are done. If sep is not specified, any whitespace string
  349. is a separator.
  350. """
  351. return []
  352.  
  353. def rstrip(self, chars=None): # real signature unknown; restored from __doc__
  354. """
  355. S.rstrip([chars]) -> str
  356.  
  357. Return a copy of the string S with trailing whitespace removed.
  358. If chars is given and not None, remove characters in chars instead.
  359. """
  360. return ""
  361.  
  362. def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
  363. """
  364. S.split(sep=None, maxsplit=-1) -> list of strings
  365.  
  366. Return a list of the words in S, using sep as the
  367. delimiter string. If maxsplit is given, at most maxsplit
  368. splits are done. If sep is not specified or is None, any
  369. whitespace string is a separator and empty strings are
  370. removed from the result.
  371. """
  372. return []
  373.  
  374. def splitlines(self, keepends=None): # real signature unknown; restored from __doc__
  375. """
  376. S.splitlines([keepends]) -> list of strings
  377.  
  378. Return a list of the lines in S, breaking at line boundaries.
  379. Line breaks are not included in the resulting list unless keepends
  380. is given and true.
  381. """
  382. return []
  383.  
  384. def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
  385. """
  386. S.startswith(prefix[, start[, end]]) -> bool
  387.  
  388. Return True if S starts with the specified prefix, False otherwise.
  389. With optional start, test S beginning at that position.
  390. With optional end, stop comparing S at that position.
  391. prefix can also be a tuple of strings to try.
  392. """
  393. return False
  394.  
  395. def strip(self, chars=None): # real signature unknown; restored from __doc__
  396. """
  397. S.strip([chars]) -> str
  398.  
  399. Return a copy of the string S with leading and trailing
  400. whitespace removed.
  401. If chars is given and not None, remove characters in chars instead.
  402. """
  403. return ""
  404.  
  405. def swapcase(self): # real signature unknown; restored from __doc__
  406. """
  407. S.swapcase() -> str
  408.  
  409. Return a copy of S with uppercase characters converted to lowercase
  410. and vice versa.
  411. """
  412. return ""
  413.  
  414. def title(self): # real signature unknown; restored from __doc__
  415. """
  416. S.title() -> str
  417.  
  418. Return a titlecased version of S, i.e. words start with title case
  419. characters, all remaining cased characters have lower case.
  420. """
  421. return ""
  422.  
  423. def translate(self, table): # real signature unknown; restored from __doc__
  424. """
  425. S.translate(table) -> str
  426.  
  427. Return a copy of the string S in which each character has been mapped
  428. through the given translation table. The table must implement
  429. lookup/indexing via __getitem__, for instance a dictionary or list,
  430. mapping Unicode ordinals to Unicode ordinals, strings, or None. If
  431. this operation raises LookupError, the character is left untouched.
  432. Characters mapped to None are deleted.
  433. """
  434. return ""
  435.  
  436. def upper(self): # real signature unknown; restored from __doc__
  437. """
  438. S.upper() -> str
  439.  
  440. Return a copy of S converted to uppercase.
  441. """
  442. return ""
  443.  
  444. def zfill(self, width): # real signature unknown; restored from __doc__
  445. """
  446. S.zfill(width) -> str
  447.  
  448. Pad a numeric string S with zeros on the left, to fill a field
  449. of the specified width. The string S is never truncated.
  450. """
  451. return ""

str

  1. #range创建连续的数字
  2.  
  3. for item in range(0,100):
  4. print(item)
  5. #设置步长
  6. for item in range(0,100,2):
  7. print(item)

range

  1. # -*- coding:utf-8 -*-
  2. # Author:sunhao
  3.  
  4. name=input('username:')
  5. age=int(input('age:'))
  6. job=input('job:')
  7. salary=int(input('salary:'))
  8.  
  9. info='''
  10. --------info of %s----------
  11. Name:%s
  12. Age:%d
  13. Job:%s
  14. Salary:%d
  15. '''%(name,name,age,job,salary) #第一种表示方法
  16.  
  17. info2='''
  18. --------info of {_name}----------
  19. Name:{_name}
  20. Age:{_age}
  21. Job:{_job}
  22. Salary:{_salary}
  23. '''.format(_name=name,
  24. _age=age,
  25. _job=job,
  26. _salary=salary) #第二种表示方法 .format()
  27.  
  28. info3='''
  29. --------info of {0}----------
  30. Name:{0}
  31. Age:{1}
  32. Job:{2}
  33. Salary:{3}
  34. '''.format(name,
  35. age,
  36. job,
  37. salary) #第三种表示方法
  38.  
  39. print(info1)
  40. print(info2)
  41. print(info3)
  42.  
  43. #三种显示结果是一样的

format()使用方法

3、列表

通过list类创建的对象

names=['Lily','Tom','Lucy','Hanmeimei']

通过下标访问列表中的元素,下标从0开始:

  1. In[3]: names = ['Lily', 'Tom', 'Lucy', 'Hanmeimei']
  2.  
  3. In[4]: names[0]
  4. Out[4]: 'Lily'
  5.  
  6. In[5]: names[1]
  7. Out[5]: 'Tom'
  8.  
  9. In[6]: names[-1]
  10. Out[6]: 'Hanmeimei'
  11.  
  12. In[7]: names[-2]
  13. Out[7]: 'Lucy'
  1. >>> names = ["Alex","Tenglan","Eric","Rain","Tom","Amy"]
  2. >>> names[1:4] #取下标1至下标4之间的数字,包括1,不包括4
  3. ['Tenglan', 'Eric', 'Rain']
  4. >>> names[1:-1] #取下标1至-1的值,不包括-1
  5. ['Tenglan', 'Eric', 'Rain', 'Tom']
  6. >>> names[0:3]
  7. ['Alex', 'Tenglan', 'Eric']
  8. >>> names[:3] #如果是从头开始取,0可以忽略,跟上句效果一样
  9. ['Alex', 'Tenglan', 'Eric']
  10. >>> names[3:] #如果想取最后一个,必须不能写-1,只能这么写
  11. ['Rain', 'Tom', 'Amy']
  12. >>> names[3:-1] #这样-1就不会被包含了
  13. ['Rain', 'Tom']
  14. >>> names[0::2] #后面的2是代表,每隔一个元素,就取一个
  15. ['Alex', 'Eric', 'Tom']
  16. >>> names[::2] #和上句效果一样
  17. ['Alex', 'Eric', 'Tom']

切片

  1. list.append() #列表追加元素 只是追加在列表的尾部
  2.  
  3. list1=['apple','orange','peach','watermelon']
  4.  
  5. list1.append('banana') #往列表中添加一个元素
  6.  
  7. print (list1)
  8. ['apple', 'orange', 'peach', 'watermelon', 'banana']

追加元素

  1. 不能批量插入
  2.  
  3. list.insert(index, object) #往列表中插入一个元素
  4.  
  5. 例如:
  6.  
  7. list1=['apple','orange','peach','watermelon']
  8.  
  9. list1.insert(1,'Lemon') #在列表第一个位置插入Lemon这个元素
  10.  
  11. print (list1)
  12.  
  13. ['apple', 'Lemon', 'orange', 'peach', 'watermelon', 'banana']

insert插入元素

  1. list1=['apple','orange','peach','watermelon']
  2.  
  3. list1[2]='fruit' #把peach修改为fruit
  4.  
  5. print(list1)
  6.  
  7. 输出:
  8. ['apple', 'Lemon', 'fruit', 'peach', 'watermelon', 'banana'] #peach被修改为 fruit

修改

  1. 删除有两种方法:
  2.  
  3. 第一种 list.remove()
  4.  
  5. list1=['apple', 'Lemon', 'orange', 'peach', 'watermelon', 'banana']
  6.  
  7. list1.remove('apple') #remove方法
  8.  
  9. 输出:
  10. print (list1)
  11.  
  12. ['Lemon', 'fruit', 'peach', 'watermelon', 'banana']  
  13.  
  14. 第二种 按下标方法删除
  15.  
  16. del list1[1] #删除列表中第1个元素

remove删除

  1. list.pop() # 默认是从列表中一次弹出最后一个元素
  2.  
  3. list.pop(1) # 如果输入下标 等于 del list1[1] 方法

pop弹出元素

  1. list.index() #查找元素的位置
  2.  
  3. list1=['Lemon', 'fruit', 'peach', 'watermelon', 'banana']
  4.  
  5. list1.index('peach') #查找peach的位置
  6.  
  7. 输出:2 #索引的位置为2
  8.  
  9. print(list1[list1.index('peach')])
  10.  
  11. 输出:peach

index索引查找元素的位置

  1. 如果一个列表中有重复的元素,需要统计重复元素的个数
  2.  
  3. list.count()
  4. 例如:
  5.  
  6. list1=['banana','peach','watermelon','banana','peach','apple','banana']
  7.  
  8. list1.count('banana') #统计列表中banana 的数量
  9.  
  10. 输出:
  11. 3

count统计元素重复个数

  1. list.clear()

clear清空列表

  1. list.reverse()
  2.  
  3. list1=['banana', 'peach', 'watermelon', 'banana','peach','apple','tomato','banana']
  4.  
  5. list1.reverse()
  6.  
  7. print (list1)
  8.  
  9. ['banana', 'tomato', 'apple', 'peach', 'banana', 'watermelon', 'peach', 'banana'] #元素反转 位置改变

reverse元素反转

  1. list.sort()
  2.  
  3. list1=['banana', 'peach', 'watermelon', 'banana','peach','apple','tomato','banana']
  4.  
  5. list1.sort()
  6.  
  7. print(list1)
  8.  
  9. ['apple', 'banana', 'banana', 'banana', 'peach', 'peach', 'tomato', 'watermelon'] #按照字母排序

sort元素排序

  1. list.extend()
  2.  
  3. #两个列表
  4. list1=['banana', 'peach', 'watermelon', 'banana','peach','apple','tomato','banana']
  5.  
  6. list2=['lily','Lucy','Tom']
  7.  
  8. list1.extend(list2) #把list1和list2合并
  9.  
  10. print(list1)
  11.  
  12. 输出:
  13. ['apple', 'banana', 'banana', 'banana', 'peach', 'peach', 'tomato', 'watermelon', 'lily', 'Lucy', 'Tom'] # 两个列表合并

extend多个列表合并元素

  1. names=['lucy','Lily','Jim','age']
  2.  
  3. new_names="".join(names)
  4. print(new_names)

列表转换成字符串

4、元组(不可变列表)

元组一级元素不可被修改和删除。但是,元组中嵌套列表可以被修改

  1. tu3=(111,222,[(333,444)],555,(666,777),)
  2.  
  3. tu3[2][0]=888
  4. print(tu3)
  5. #输出:(111, 222, [888], 555, (666, 777))

创建元组:

  1. tuple=('tom','lily',1,2,) 一般写元组时,建议在最后加一个逗号
  1. class tuple(object):
  2. """
  3. tuple() -> empty tuple
  4. tuple(iterable) -> tuple initialized from iterable's items
  5.  
  6. If the argument is a tuple, the return value is the same object.
  7. """
  8. def count(self, value): # real signature unknown; restored from __doc__
  9. """ T.count(value) -> integer -- return number of occurrences of value """
  10. return 0
  11.  
  12. def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
  13. """
  14. T.index(value, [start, [stop]]) -> integer -- return first index of value.
  15. Raises ValueError if the value is not present.
  16. """
  17. return 0
  18.  
  19. def __add__(self, *args, **kwargs): # real signature unknown
  20. """ Return self+value. """
  21. pass
  22.  
  23. def __contains__(self, *args, **kwargs): # real signature unknown
  24. """ Return key in self. """
  25. pass
  26.  
  27. def __eq__(self, *args, **kwargs): # real signature unknown
  28. """ Return self==value. """
  29. pass
  30.  
  31. def __getattribute__(self, *args, **kwargs): # real signature unknown
  32. """ Return getattr(self, name). """
  33. pass
  34.  
  35. def __getitem__(self, *args, **kwargs): # real signature unknown
  36. """ Return self[key]. """
  37. pass
  38.  
  39. def __getnewargs__(self, *args, **kwargs): # real signature unknown
  40. pass
  41.  
  42. def __ge__(self, *args, **kwargs): # real signature unknown
  43. """ Return self>=value. """
  44. pass
  45.  
  46. def __gt__(self, *args, **kwargs): # real signature unknown
  47. """ Return self>value. """
  48. pass
  49.  
  50. def __hash__(self, *args, **kwargs): # real signature unknown
  51. """ Return hash(self). """
  52. pass
  53.  
  54. def __init__(self, seq=()): # known special case of tuple.__init__
  55. """
  56. tuple() -> empty tuple
  57. tuple(iterable) -> tuple initialized from iterable's items
  58.  
  59. If the argument is a tuple, the return value is the same object.
  60. # (copied from class doc)
  61. """
  62. pass
  63.  
  64. def __iter__(self, *args, **kwargs): # real signature unknown
  65. """ Implement iter(self). """
  66. pass
  67.  
  68. def __len__(self, *args, **kwargs): # real signature unknown
  69. """ Return len(self). """
  70. pass
  71.  
  72. def __le__(self, *args, **kwargs): # real signature unknown
  73. """ Return self<=value. """
  74. pass
  75.  
  76. def __lt__(self, *args, **kwargs): # real signature unknown
  77. """ Return self<value. """
  78. pass
  79.  
  80. def __mul__(self, *args, **kwargs): # real signature unknown
  81. """ Return self*value.n """
  82. pass
  83.  
  84. @staticmethod # known case of __new__
  85. def __new__(*args, **kwargs): # real signature unknown
  86. """ Create and return a new object. See help(type) for accurate signature. """
  87. pass
  88.  
  89. def __ne__(self, *args, **kwargs): # real signature unknown
  90. """ Return self!=value. """
  91. pass
  92.  
  93. def __repr__(self, *args, **kwargs): # real signature unknown
  94. """ Return repr(self). """
  95. pass
  96.  
  97. def __rmul__(self, *args, **kwargs): # real signature unknown
  98. """ Return self*value. """
  99. pass

tuple方法

  1. str1="Mypython"
  2.  
  3. tu1=tuple(str1)
  4.  
  5. print(tu1)
  6.  
  7. #输出:('M', 'y', 'p', 'y', 't', 'h', 'o', 'n')

字符串转换成元组

  1. names=['lucy','Lily','Jim','age']
  2.  
  3. tu2=tuple(names)
  4. print(tu2)
  5. #输出:('lucy', 'Lily', 'Jim', 'age')

列表转换成元组

  1. name2=('lucy', 'Lily', 'Jim', 'age')
  2.  
  3. list1=list(name2)
  4.  
  5. print(list1)
  6. #输出:['lucy', 'Lily', 'Jim', 'age']

元组转换成列表

5、字典

字典一种key - value 的数据类型

字典的特性:

  • dict是无序的
  • key必须是唯一的,所以自动去重

语法:

  1. user_info={
  2. '':'Tom',
  3. '':'Jim',
  4. '':'Lucy',
  5. '':'Lily'
  6. }
  1. a = user_info.keys()
  2. print(a)

获取所有的key列表keys()

  1. #根据key获取值
  2. a = user_info.get("age")
  3. print(a)
  4.  
  5. #如果没有值,返回None,不报错
  6.  
  7. a = user_info.get("Age",19")
  8. print(a)
  9.  
  10. #如果没有值,就返回19

根据key获取值get()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6.  
  7. print(user_info.values())
  8.  
  9. #返回 dict_values(['nick', 18, 'pythoner'])

获取所有的value列表values()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6.  
  7. print(user_info.items())
  8.  
  9. #输出:dict_items([('name', 'nick'), ('age', 18), ('job', 'pythoner')])

items()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6. #第一种删除方法
  7. print(user_info.pop('name'))
  8.  
  9. #输出{'age': 18, 'job': 'pythoner'}
  10.  
  11. #第二种随机删除字典里的key和value
  12.  
  13. print(user_info.popitem())

删除pop()和随机删除popitem()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6. user_info2 = {
  7. "wage":800000000,
  8. "drem":"The knife girl",
  9. "name":"jack"
  10. }
  11. #有交叉的就覆盖了 没有交叉就创建
  12. user_info.update(user_info2)
  13.  
  14. print(user_info)
  15. #输出:{'name': 'jack', 'age': 18, 'job': 'pythoner', 'wage': 800000000, 'drem': 'The knife girl'}

两个字典更新update()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6. #如果key不存在,则创建,如果存在,则返回已存在的值且不修改
  7.  
  8. print(user_info.setdefault('slary',5000))
  9. print(user_info)

setdefault()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6.  
  7. print(user_info.clear())
  8. print(user_info)
  9.  
  10. #输出:{}

清空字典clear()

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6.  
  7. del user_info['name']
  8.  
  9. print(user_info)
  10.  
  11. #输出:{'age': 18, 'job': 'pythoner'}

del删除元素

  1. #根据序列,创建字典并指定统一的值
  2.  
  3. info=dict.fromkeys(['slary','number'],5000)
  4.  
  5. print(info)
  6.  
  7. #输出:{'slary': 5000, 'number': 5000}

dict.fromkeys()

  1. province={
  2.  
  3. '广东省':{'深圳市':['南山区','龙岗区','福田区'],
  4. '广州市':['荔湾区','海珠区','天河区'],
  5. '惠州市':['惠阳区','惠城区','惠东县']},
  6.  
  7. '浙江省':{'杭州市':['西湖区','上城区','下城区'],
  8. '宁波市':['江北区','镇海区'],
  9. '嘉兴市':['南湖区','秀洲区']}
  10. }
  11.  
  12. print(province['广东省'])
  13.  
  14. {'深圳市': ['南山区', '龙岗区', '福田区'], '广州市': ['荔湾区', '海珠区', '天河区'], '惠州市': ['惠阳区', '惠城区', '惠东县']}

多级字典嵌套及操作

  1. province={
  2.  
  3. '广东省':{'深圳市':['南山区','龙岗区','福田区'],
  4. '广州市':['荔湾区','海珠区','天河区'],
  5. '惠州市':['惠阳区','惠城区','惠东县']},
  6.  
  7. '浙江省':{'杭州市':['西湖区','上城区','下城区'],
  8. '宁波市':['江北区','镇海区'],
  9. '嘉兴市':['南湖区','秀洲区']}
  10. }
  11.  
  12. for k,v in province.items():
  13. print(k,v)

字典for循环

  1. user_info = {
  2. "name":"nick",
  3. "age":18,
  4. "job":"pythoner"
  5. }
  6. user_info2 = {
  7. "wage":800000000,
  8. "drem":"The knife girl",
  9. "name":"jack"
  10. }
  11. #有交叉的就覆盖了 没有交叉就创建
  12. user_info.update(user_info2)
  13. 或者
  14. user_info.update( "wage"=800000000, "drem"="The knife girl")
  15.  
  16. print(user_info)
  17. #输出:{'name': 'jack', 'age': 18, 'job': 'pythoner', 'wage': 800000000, 'drem': 'The knife girl'}

update()补充

6、set()集合

集合是一个无序的,不重复的数据组合,它的主要作用如下:

  • 去重,把一个列表变成集合,就自动去重了
  • 关系测试,测试两组数据之前的交集、差集、并集等关系
  • 集合中元素必须是不可变类型,不能包含列表、字典
  • 集合只可以追加、删除,但是不可修改
  1. #列表
  2. list1=[1,4,5,7,3,6,7,9]
  3.  
  4. # 创建集合 集合也是无序的
  5. set1=set(list1)
  6.  
  7. print(set1,type(set1))
  8.  
  9. set2=set([2,6,0,66,22,8,4])
  10.  
  11. print(set1,set2)
  12.  
  13. #输出:
  14. {1, 3, 4, 5, 6, 7, 9} <class 'set'>
  15. {1, 3, 4, 5, 6, 7, 9} {0, 2, 66, 4, 6, 8, 22}

创建集合

  1. list1=[1,4,5,7,3,6,7,9]
  2.  
  3. set1=set(list1)
  4.  
  5. set2=set([2,6,0,66,22,8,4])
  6.  
  7. print(set1.intersection(set2))
  8.  
  9. #输出:{4, 6}

交集intersection()

  1. list1=[1,4,5,7,3,6,7,9]
  2.  
  3. set1=set(list1)
  4.  
  5. set2=set([2,6,0,66,22,8,4])
  6.  
  7. #求并集两个集合去重合并
  8.  
  9. print(set1.union(set2))
  10. #输出:{0, 1, 2, 3, 4, 5, 6, 7, 66, 9, 8, 22}

并集union()

  1. list1=[1,4,5,7,3,6,7,9]
  2.  
  3. set1=set(list1)
  4.  
  5. set2=set([2,6,0,66,22,8,4])
  6.  
  7. #set1中有 set2中没有的元素
  8. print(set1.difference(set2))
  9.  
  10. #输出:{1, 3, 5, 7, 9}
  11.  
  12. #set2中有 set1中没有的元素
  13. print(set2.difference(set1))
  14.  
  15. #输出:{0, 2, 66, 8, 22}

差集difference()

  1. list1=[1,4,5,7,3,6,7,9]
  2.  
  3. set1=set(list1)
  4.  
  5. set2=set([2,6,0,66,22,8,4])
  6.  
  7. #求子集
  8.  
  9. #判断set1是否是set2的子集
  10. print(set1.issubset(set2))
  11.  
  12. #判断set2是否是set1的子集
  13. print(set2.issubset(set1))

子集issubset()

  1. #求父集
  2.  
  3. list1=[1,4,5,7,3,6,7,9]
  4.  
  5. set1=set(list1)
  6.  
  7. set2=set([2,6,0,66,22,8,4])
  8.  
  9. # 判断set1是否是set2的父集
  10. print(set1.issuperset(set2))
  11.  
  12. # 判断set2是否是set1的父集
  13. print(set2.issuperset(set1))

父集issuperset()

  1. list1=[1,4,5,7,3,6,7,9]
  2.  
  3. set1=set(list1)
  4.  
  5. set2=set([2,6,0,66,22,8,4])
  6.  
  7. #对称差集
  8.  
  9. print(set1.symmetric_difference(set2))
  10.  
  11. #输出:
  12. {0, 1, 2, 66, 3, 5, 8, 7, 9, 22}

对称差集symmetric_difference()

  1. list1=[1,4,5,7,3,6,7,9]
  2.  
  3. set1=set(list1)
  4.  
  5. set2=set([2,6,0,66,22,8,4])
  6.  
  7. #如果两个集合没有交集返回True 否则返回False
  8.  
  9. print(set1.isdisjoint(set2))
  10.  
  11. #输出:False

两个集合没有交集返回True

  1. print(set1 & set2) #交集
  2.  
  3. print(set1 | set2) #并集
  4.  
  5. print(set1 - set2) #差集
  6.  
  7. print(set1 ^ set2) #对称差集
  8.  
  9. list1=[1,4,5,7,3,6,7,9]
  10.  
  11. set1=set(list1)
  12.  
  13. set2=set([2,6,0,66,22,8,4])
  14.  
  15. #集合中是没有插入的,只能添加
  16.  
  17. set1.add(2) # 添加一项
  18.  
  19. set3 = set([100, 200, 300])
  20.  
  21. set1.update(set3) # 只能把一个集合更新到另一个集合中
  22.  
  23. set1.remove(100) # 删除集合中一个元素
  24. set1.discard(100) # 删除一个元素 如果这个元素没有 不会报错 而remove会报错

集合其他基本操作

  1. # -*-coding:utf-8-*-
  2. # Author:sunhao
  3.  
  4. product_list=[('Iphone',5800),
  5. ('Mac Pro',12000),
  6. ('Bike',800),
  7. ('Watch',10600),
  8. ('coffee',31)
  9. ]
  10. shopping_list=[]
  11.  
  12. salary=input('请输入你的工资:')
  13. if salary.isdigit():
  14. salary=int(salary)
  15. while True:
  16. for index,item in enumerate(product_list):
  17. print(index,item)
  18. user_choice=input("请选择要买的商品:")
  19. if user_choice.isdigit():
  20. user_choice=int(user_choice)
  21. if user_choice<len(product_list) and user_choice >=0:
  22. p_item=product_list[user_choice]
  23. print(p_item)
  24. if p_item[1] <= salary:
  25. shopping_list.append(p_item)
  26. salary -= p_item[1]
  27. print('%s已添加至购物车 ,余额为%d'%(p_item[0],salary))
  28.  
  29. else:
  30. print("\033[41;1m你的余额只剩%s\033[0m"%salary)
  31.  
  32. else:
  33. print("商品不存在")
  34.  
  35. elif user_choice=='q':
  36. print("-------shoppinglist------")
  37. for p in shopping_list:
  38. print(p[0])
  39. print('-------------------------')
  40. print('Your current balance:%s'%salary)
  41. exit()
  42. else:
  43. print('Invalid choice')

练习-购物车程序

三、文件处理

1、文件操作

对文件操作流程

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件
  1. Somehow, it seems the love I knew was always the most destructive kind
  2. 不知为何,我经历的爱情总是最具毁灭性的的那种
  3. Yesterday when I was young
  4. 昨日当我年少轻狂
  5. The taste of life was sweet
  6. 生命的滋味是甜的
  7. As rain upon my tongue
  8. 就如舌尖上的雨露
  9. I teased at life as if it were a foolish game
  10. 我戏弄生命 视其为愚蠢的游戏
  11. The way the evening breeze
  12. 就如夜晚的微风
  13. May tease the candle flame
  14. 逗弄蜡烛的火苗
  15. The thousand dreams I dreamed
  16. 我曾千万次梦见
  17. The splendid things I planned
  18. 那些我计划的绚丽蓝图
  19. I always built to last on weak and shifting sand
  20. 但我总是将之建筑在易逝的流沙上
  21. I lived by night and shunned the naked light of day
  22. 我夜夜笙歌 逃避白昼赤裸的阳光
  23. And only now I see how the time ran away
  24. 事到如今我才看清岁月是如何匆匆流逝
  25. Yesterday when I was young
  26. 昨日当我年少轻狂
  27. So many lovely songs were waiting to be sung
  28. 有那么多甜美的曲儿等我歌唱
  29. So many wild pleasures lay in store for me
  30. 有那么多肆意的快乐等我享受
  31. And so much pain my eyes refused to see
  32. 还有那么多痛苦 我的双眼却视而不见
  33. I ran so fast that time and youth at last ran out
  34. 我飞快地奔走 最终时光与青春消逝殆尽
  35. I never stopped to think what life was all about
  36. 我从未停下脚步去思考生命的意义
  37. And every conversation that I can now recall
  38. 如今回想起的所有对话
  39. Concerned itself with me and nothing else at all
  40. 除了和我相关的 什么都记不得了
  41. The game of love I played with arrogance and pride
  42. 我用自负和傲慢玩着爱情的游戏
  43. And every flame I lit too quickly, quickly died
  44. 所有我点燃的火焰都熄灭得太快
  45. The friends I made all somehow seemed to slip away
  46. 所有我交的朋友似乎都不知不觉地离开了
  47. And only now I'm left alone to end the play, yeah
  48. 只剩我一个人在台上来结束这场闹剧
  49. Oh, yesterday when I was young
  50. 噢 昨日当我年少轻狂
  51. So many, many songs were waiting to be sung
  52. 有那么那么多甜美的曲儿等我歌唱
  53. So many wild pleasures lay in store for me
  54. 有那么多肆意的快乐等我享受
  55. And so much pain my eyes refused to see
  56. 还有那么多痛苦 我的双眼却视而不见
  57. There are so many songs in me that won't be sung
  58. 我有太多歌曲永远不会被唱起
  59. I feel the bitter taste of tears upon my tongue
  60. 我尝到了舌尖泪水的苦涩滋味
  61. The time has come for me to pay for yesterday
  62. 终于到了付出代价的时间 为了昨日
  63. When I was young
  64. 当我年少轻狂

文件示例lyrics

  1. f = open('lyrics','w','encoding=utf-8') #打开文件 f为文件句柄
  2.  
  3. data = f.read() #读文件
  4.  
  5. print(data)
  6.  
  7. f.close() #关闭文件
  8.  
  9. f.readable() #判断文件是否可读
  10.  
  11. f.writable() #判断文件是都可写
  12.  
  13. f.closed() #判断文件是否关闭 返回True 和 False
  1. 打开一个文件包含两部分资源:操作系统级打开的文件+应用程序的变量。在操作完毕一个文件时,必须把与该文件的这两部分资源一个不落地回收,回收方法为:
  2. 1f.close() #回收操作系统级打开的文件
  3. 2del f #回收应用程序级的变量
  4.  
  5. 其中del f一定要发生在f.close()之后,否则就会导致操作系统打开的文件还没有关闭,白白占用资源,
  6. python自动的垃圾回收机制决定了我们无需考虑del f,这就要求我们,在操作完毕文件后,一定要记住f.close()
  7.  
  8. 我们推荐傻瓜式操作方式:使用with关键字来帮我们管理上下文
  9. with open('a.txt','w') as f:
  10. pass
  11.  
  12. with open('a.txt','r') as read_f,open('b.txt','w') as write_f:
  13. data=read_f.read()
  14. write_f.write(data)

注意f.close()

  1. f=open(...)是由操作系统打开文件,那么如果我们没有为open指定编码,那么打开文件的默认编码很明显是操作系统说了算了,操作系统会用自己的默认编码去打开文件,在windows下是gbk,在linux下是utf-8
  2. 这就用到了上节课讲的字符编码的知识:若要保证不乱码,文件以什么方式存的,就要以什么方式打开。
  3.  
  4. f=open('a.txt','r',encoding='utf-8')

打开文件注意字符编码

2、打开文件的模式

  1. #1. 打开文件的模式有(默认为文本模式):
  2. r,只读模式【默认模式,文件必须存在,不存在则抛出异常】
  3. w,只写模式【不可读;不存在则创建;存在则清空内容】
  4. a,只追加写模式【不可读;不存在则创建;存在则只追加内容】
  5.  
  6. #2. 对于非文本文件,我们只能使用b模式,"b"表示以字节的方式操作(而所有文件也都是以字节的形式存储的,使用这种模式无需考虑文本文件的字符编码、图片文件的jgp格式、视频文件的avi格式)
  7. rb
  8. wb
  9. ab
  10. 注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码
  11.  
  12. #3. 了解部分
  13. "+" 表示可以同时读写某个文件
  14. r+, 读写【可读,可写】
  15. w+,写读【可读,可写】
  16. a+, 写读【可读,可写】

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)

rU

r+U

  1. x 只写模式【不可读;不存在则创建,存在则报错】
  2. x+ ,写读【可读,可写】
  3. xb

3、操作文件的方法

  1. f.read() #读取所有内容,光标移动到文件末尾
  2. f.readline() #读取一行内容,光标移动到第二行首部
  3. f.readlines() #读取每一行内容,存放于列表中
  4.  
  5. f.write('1111\n222\n') #针对文本模式的写,需要自己写换行符
  6. f.write('1111\n222\n'.encode('utf-8')) #针对b模式的写,需要自己写换行符
  7. f.writelines(['333\n','444\n']) #文件模式
  8. f.writelines([bytes('333\n',encoding='utf-8'),'444\n'.encode('utf-8')]) #b模式
  1. f = open('lyrics','r+',encoding='utf-8')
  2.  
  3. for index,line in enumerate(f.readlines()):
  4.  
  5. if index ==9:
  6. print(-------分隔符------) #第九行打印分隔符 跳出本次循环
  7. continue
  8. print(line)

示例

练习,利用b模式,编写一个cp工具,要求如下:

  1. 既可以拷贝文本又可以拷贝视频,图片等文件

  2. 用户一旦参数错误,打印命令的正确使用方法,如usage: cp source_file target_file

  提示:可以用import sys,然后用sys.argv获取脚本后面跟的参数

  1. import sys
  2. if len(sys.argv) != 3:
  3. print('usage: cp source_file target_file')
  4. sys.exit()
  5.  
  6. source_file,target_file=sys.argv[1],sys.argv[2]
  7. with open(source_file,'rb') as read_f,open(target_file,'wb') as write_f:
  8. for line in read_f:
  9. write_f.write(line)

练习

4、文件内光标移动

  1. f = open('lyrics','r+',encoding='utf-8')
  2.  
  3. print(f.tell())
  4.  
  5. f.read(16)
  6.  
  7. print(f.tell())
  8.  
  9. 输出:
  10. 0
  11. 16

tell()查看文件句柄指针的位置

  1. f = open('lyrics','r+',encoding='utf-8')
  2.  
  3. print(f.tell())
  4.  
  5. f.read(16)
  6.  
  7. print(f.tell())
  8.  
  9. f.seek(0) #移动到文件字符行首
  10.  
  11. print(f.tell())
  12. 输出:
  13. 0
  14. 16

seek()移动文件句柄指针位置

  1. f = open('lyrics','r+',encoding='utf-8')
  2.  
  3. print(f.encoding())
  4.  
  5. 输出:
  6. utf-8

encoding()打印文件的编码

  1. f = open('lyrics','r+',encoding='utf-8')
  2.  
  3. f.flush()

flush()强制刷新到硬盘

  1. # -*-coding:utf-8-*-
  2. import sys,time
  3.  
  4. for i in range(10):
  5. sys.stdout.write('#')
  6.  
  7. sys.stdout.flush() 如果不加flush 是等缓存满了之后一次性打印出来 加了之后是打印在一次强制刷新一次
  8. time.sleep(1)

flush()示例-打印进度条

  1. truncate是截断文件,所以文件的打开方式必须可写,但是不能用ww+等方式打开,因为那样直接清空文件了,所以truncate要在r+或aa+等模式下测试效果

truncate()截断文件

5、文件的修改

文件的数据是存放于硬盘上的,因而只存在覆盖、不存在修改这么一说,我们平时看到的修改文件,都是模拟出来的效果,具体的说有两种实现方式:

方式一:将硬盘存放的该文件的内容全部加载到内存,在内存中是可以修改的,修改完毕后,再由内存覆盖到硬盘(word,vim,nodpad++等编辑器)

  1. import os
  2.  
  3. with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
  4. data=read_f.read() #全部读入内存,如果文件很大,会很卡
  5. data=data.replace('alex','SB') #在内存中完成修改
  6.  
  7. write_f.write(data) #一次性写入新文件
  8.  
  9. os.remove('a.txt')
  10. os.rename('.a.txt.swap','a.txt')

方式二:将硬盘存放的该文件的内容一行一行地读入内存,修改完毕就写入新文件,最后用新文件覆盖源文件

  1. import os
  2.  
  3. with open('a.txt') as read_f,open('.a.txt.swap','w') as write_f:
  4. for line in read_f:
  5. line=line.replace('alex','SB')
  6. write_f.write(line)
  7.  
  8. os.remove('a.txt')
  9. os.rename('.a.txt.swap','a.txt')
  1. # -*-coding:utf-8-*-
  2. # Author:sunhao
  3.  
  4. f = open('yesterday','r',encoding='utf-8') #打开要修改的文件
  5.  
  6. f_new = open('yesterday.bak','w',encoding='utf-8') #再打开一个要写入的新文件
  7.  
  8. for line in f: #循环旧文件里的每一行
  9. if "肆意的快乐" in line: #每一行的type(line)是一个字符串
  10. line=line.replace("肆意的快乐",'肆意的痛苦') #字符串替换
  11.  
  12. f_new.write(line) #写入新文件
  13.  
  14. f.close() #关闭旧文件
  15. f_new.close() #关闭新文件

文件修改-示例

  1. #with语句
  2. 为了避免打开文件后忘记关闭,可以通过管理上下文,即:
  3.  
  4. with open('file','r','encoding='uth-8'') as f: #f为文件句柄
  5. for line in f:
  6. print(line)
  7.  
  8. 这样不用关闭文件
  9.  
  10. 也可以同时操作多个文件
  11. with open('file1','r','encoding=utf-8') as f1,open('file2','r','encoding=utf-8') as f2:
  12. pass

with open()管理上下文

  1. import sys
  2.  
  3. f = open('yesterday','r',encoding='utf-8')
  4.  
  5. f_new = open('yesterday.bak','w',encoding='utf-8')
  6.  
  7. find_str=sys.argv[1]
  8. replace_str=sys.argv[2]
  9.  
  10. for line in f:
  11. if find_str in line:
  12. line=line.replace(find_str,replace_str)
  13.  
  14. f_new.write(line)
  15.  
  16. f.close()
  17. f_new.close()

练习-脚本传参实现sed替换

四、其他

1、字符编码与转码

1.在python2默认编码是ASCII, python3里默认是unicode

2.unicode 分为 utf-32(占4个字节),utf-16(占两个字节),utf-8(占1-4个字节), so utf-16就是现在最常用的unicode版本, 不过在文件里存的还是utf-8,因为utf8省空间

3.在py3中encode,在转码的同时还会把string 变成bytes类型,decode在解码的同时还会把bytes变回string

  1. name='中国'
  2. new_name=name.encode('utf-8') #对字符串name编码 成二进制字节码
  3.  
  4. print (new_name)
  5.  
  6. 输出:
  7. b'\xe4\xb8\xad\xe5\x9b\xbd'

字符串编码成字节码

  1. name='中国'
  2. new_name=name.encode('utf-8') #对字符串name编码成二进制字节码
  3.  
  4. renew_name=new_name.decode() #对二进制字节码进行解码
  5.  
  6. print (renew_name)
  7.  
  8. 输出:
  9. 中国

二进制字节码解码成字符串

上图仅适用于python2

  1. #-*- encoding:utf-8 -*-
  2.  
  3. import sys
  4.  
  5. print(sys.getdefaultencoding()) #打印系统默认编码
  6.  
  7. s='你好'
  8.  
  9. s_to_unicode=s.decode('utf-8') #先解码成unicode
  10.  
  11. print(s_to_unicode,type(s_to_unicode))
  12.  
  13. s_to_gbk=s_to_unicode.encode('gbk') #再编码成gbk
  14.  
  15. print(s_to_gbk)
  16.  
  17. print('你好')
  18.  
  19. #把gbk再转成utf-8
  20.  
  21. gbk_to_utf8=s_to_gbk.decode('gbk').encode('utf-8')
  22.  
  23. print(gbk_to_utf8)

python2.X字符编码示列

  1. #在python3中默认的字符编码是unicode-utf8所以不需要decode了
  2. #-*-coding:gb2312 -*- #这个也可以去掉 #默认字符集为gb2312
  3. __author__ = 'Alex Li'
  4.  
  5. import sys
  6. print(sys.getdefaultencoding())
  7.  
  8. msg = "我爱北京天安门"
  9.  
  10. #msg_gb2312 = msg.decode("utf-8").encode("gb2312") #在python2中需要先解码成unicode再编码成gb2312
  11.  
  12. msg_gb2312 = msg.encode("gb2312") #python3中默认就是unicode utf8,不用再decode,喜大普奔
  13.  
  14. gb2312_to_unicode = msg_gb2312.decode("gb2312")
  15. gb2312_to_utf8 = msg_gb2312.decode("gb2312").encode("utf-8")
  16.  
  17. print(msg)
  18. print(msg_gb2312)
  19. print(gb2312_to_unicode)
  20. print(gb2312_to_utf8)

python3.x字符编码示例

hex()十进制转换为十六进制
hex()二进制转十六进制
  1. #十进制转二进制
  2. number=10
  3.  
  4. to_bin=bin(number)
  5. print(to_bin)
  6. #输出:0b1010
  7.  
  8. #十六进制转二进制
  9.  
  10. number=0xff
  11.  
  12. to_bin=bin(number)
  13. print(to_bin)
  14. #输出:0b11111111

bin()十进制(十六进制)转二进制

  1. #十六进制转十进制
  2. number=0xff
  3.  
  4. to_int=int(number)
  5. print(to_int)
  6. #输出:255
  7.  
  8. #二进制转十进制
  9. number=0b11111111
  10.  
  11. to_int=int(number)
  12. print(to_int)
  13. #输出:255

int()十六进制(二进制)转十进制

  1. name = "python之路"
  2.  
  3. a = bytes(name, encoding='utf-8')
  4.  
  5. print(a)
  6.  
  7. for i in a:
  8. print(i,bin(i))
  9.  
  10. b = bytes(name, encoding='gbk')
  11. print(b)
  12. for i in b:
  13. print(i, bin(i))

示例

2、三元运算符

  1. result= 1 if 条件 else 2
  2.  
  3. 如果条件为真:result=值1
  4. 如果条件为假:result=值2
  5.  
  6. a,b,c=1,4,6
  7. d= a if a>b else c

三元运算符

3、input和raw_input

  1. # -*-coding:utf-8 -*-
  2. name=raw_input('请输入你的名字:') #raw_input仅适用于python2.7版本
  3.  
  4. age=input('请输入你的年龄:')
  5.  
  6. print("%s的年龄是%s:"%(name,age))

用户输入input()和raw_input()

  1. # 输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法
  2.  
  3. import getpass #导入getpass模块
  4.  
  5. _username='sunhao'
  6. _password='abc123'
  7.  
  8. username = input("usename:")
  9.  
  10. password = getpass.getpass("password:")
  11.  
  12. if _username==username and password == _password:
  13. print("Welcome user {name} login...".format(name=_username))
  14. else:
  15. print("Invalid username or password")

getpass

Python全栈开发之2、数据类型-数值、字符串、列表、字典、元组和文件处理的更多相关文章

  1. 战争热诚的python全栈开发之路

    从学习python开始,一直是自己摸索,但是时间不等人啊,所以自己为了节省时间,决定报个班系统学习,下面整理的文章都是自己学习后,认为重要的需要弄懂的知识点,做出链接,一方面是为了自己找的话方便,一方 ...

  2. python全栈开发之路

    一.Python基础 python简介 python数据类型(数字\字符串\列表) python数据类型(元组\字典) python数据类型(集合) python占位符%s,%d,%r,%f prin ...

  3. python全栈开发之OS模块的总结

    OS模块 1. os.name()      获取当前的系统 2.os.getcwd      #获取当前的工作目录 import os cwd=os.getcwd() # dir=os.listdi ...

  4. Python全栈开发之3、数据类型set补充、深浅拷贝与函数

    转载请注明出处http://www.cnblogs.com/Wxtrkbc/p/5466082.html 一.基本数据类型补充 set是一个无序而且不重复的集合,有些类似于数学中的集合,也可以求交集, ...

  5. Python全栈开发之14、Javascript

    一.简介 前面我们学习了html和css,但是我们写的网页不能动起来,如果我们需要网页出现各种效果,那么我们就要学习一门新的语言了,那就是JavaScript,JavaScript是世界上最流行的脚本 ...

  6. Python全栈开发之MySQL(二)------navicate和python操作MySQL

    一:Navicate的安装 1.什么是navicate? Navicat是一套快速.可靠并价格相宜的数据库管理工具,专为简化数据库的管理及降低系统管理成本而设.它的设计符合数据库管理员.开发人员及中小 ...

  7. Python全栈开发之5、模块

    一.模块 1.import导入模块 #1.定义 模块:用来从逻辑上组织python代码(变量,函数,类,逻辑),本质就是.py结尾的python文件,实现一个功能 包:python package 用 ...

  8. Python全栈开发之1、输入输出与流程控制

    Python简介 python是吉多·范罗苏姆发明的一种面向对象的脚本语言,可能有些人不知道面向对象和脚本具体是什么意思,但是对于一个初学者来说,现在并不需要明白.大家都知道,当下全栈工程师的概念很火 ...

  9. Python全栈开发之21、django

    http://www.cnblogs.com/wupeiqi/articles/5237704.html http://www.cnblogs.com/wupeiqi/articles/5246483 ...

随机推荐

  1. EntityManager的基本方法

    1.Persistence 主要用来获取EntityManagerFactory的实例; 通过静态方法:createEntityManagerFactory 来实现: 该方法有两个重载版本:     ...

  2. CSS的水平居中和垂直居中

    水平居中如果不太熟悉盒子模型的话属实不太好理解,其实就是控制其他属性来让border之内的内容被控制在父容器中间就行了,最经典的就是使用{margin: 0  auto}了,控制其上下外边框为0,左右 ...

  3. Android源码开发利器——Java源码调试(基于4.1.2)

     原文地址:http://blog.csdn.net/jinzhuojun/article/details/8868038     调试Android Java源码 草帽的后花园——Neo 写在之前的 ...

  4. 「Luogu P5601」小D与笔试

    题目链接 戳我 \(Solution\) 这道题官方题解的做法太复杂了,还需要扫字符串. 其实只需要两个\(map\)就好了. 一个\(map<string,stirng>\)用来记录题目 ...

  5. DB 分库分表(1):拆分实施策略和示例演示

    DB 分库分表(1):拆分实施策略和示例演示 第一部分:实施策略 1.准备阶段 对数据库进行分库分表(Sharding化)前,需要开发人员充分了解系统业务逻辑和数据库schema.一个好的建议是绘制一 ...

  6. SpringMVC接收请求参数和页面传参

    接收请求参数: 1,使用HttpServletRequest获取 @RequestMapping("/login.do") public String login(HttpServ ...

  7. Java 注解方式校验请求参数

    1. 参数校验常用注解          注解 验证的数据类型 备注                              Null   任意类型  参数值必须是 Null  NotNull   ...

  8. 邻居子系统 之 邻居项查找neigh_lookup、___neigh_lookup_noref

    概述 邻居项查找是通过neigh_lookup相关函数来进行的: ___neigh_lookup_noref,该函数根据输出设备和主键值(IPv4为下一跳ip地址)在邻居项hash表中查找,找到则返回 ...

  9. redis如何清空当前缓存和所有缓存

    Windows环境下使用命令行进行redis缓存清理1.redis安装目录下输入cmd2.redis-cli -p 端口号3.flushdb    清除当前数据库缓存4.flushall     清除 ...

  10. JDBC——JDBC基础

    1.JDBC与数据库的交互过程概括性来说,JDBC与数据库交互有以下这些步骤:1.建立一个到数据库的连接.2.在数据库中对表执行检索.创建,或修改的SQL查询.3.关闭到数据库的连接.JDBC的类和接 ...