You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

297 lines
3.3 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. Python and Libraries Cheatsheet
  2. ===============================
  3. Main
  4. ----
  5. ```
  6. if __name__ == '__main__':
  7. main()
  8. ```
  9. Range
  10. -----
  11. ```
  12. range(<to exclusive>)
  13. range(<from inclusive>, <to exclusive>)
  14. range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
  15. ```
  16. List
  17. ----
  18. ```
  19. <list>[<inclusive from>:<exclusive to>:<step size>]
  20. <list>.extend(<list>)
  21. <list>.sort()
  22. <list>.reverse()
  23. sum(<list>)
  24. ```
  25. Dictionary
  26. ----------
  27. <dict>.items()
  28. <dict>.get(<key>, <default>)
  29. <dict>.setdefault(<key>, <default>)
  30. ```
  31. Set
  32. ---
  33. ```
  34. <set> = set()
  35. <set>.add(<el>)
  36. <set>.update(<set>)
  37. <set>.union(<set>)
  38. <set>.intersection(<set>)
  39. <set>.difference(<set>)
  40. ```
  41. Enumerate
  42. ---------
  43. ```
  44. for i, <el> in enumerate(<list>)
  45. ```
  46. Type
  47. ----
  48. ```
  49. type(<el>) is int/str/set/list
  50. ```
  51. ```
  52. import numbers
  53. isinstance(<el>, numbers.Number)
  54. ```
  55. String
  56. ------
  57. ```
  58. str.replace(<text>, <old>, <new>)
  59. <str>.isnumeric()
  60. ```
  61. ### Print
  62. ```
  63. print(<el1>, <el2>, end='', sep='', file=<file>)
  64. ```
  65. ### Regex
  66. ```
  67. import re
  68. re.sub(<regex>, <new>, <text>)
  69. re.search(<regex>, <text>)
  70. ```
  71. ### Format
  72. ```
  73. '{}'.format(<el>)
  74. ```
  75. ```
  76. {:<min width>} -> '<el> '
  77. {:><min width>} -> ' <el>'
  78. {:^<min width>} -> ' <el> '
  79. {:_<min width>} -> '<el>____'
  80. {:.<max width>} -> '<e>'
  81. {:<max widht>.<min width>} -> ' <e>'
  82. {:<max width>.<no of decimals>f} -> ' 3.14'
  83. ```
  84. ### Text Wrap
  85. ```
  86. import textwrap
  87. textwrap.wrap(<text>, <width>)
  88. ```
  89. Random
  90. ------
  91. ```
  92. import random
  93. random.random()
  94. random.randint(<from inclusive>, <to inclusive>)
  95. random.shuffle(<list>)
  96. ```
  97. Infinity
  98. --------
  99. ```
  100. float("inf")
  101. ```
  102. Datetime
  103. --------
  104. ```
  105. import datetime
  106. now = datetime.datetime.now()
  107. now.strftime('%Y%m%d')
  108. now.strftime('%Y%m%d%H%M%S')
  109. ```
  110. Inline
  111. ------
  112. ### For
  113. ```
  114. [i+1 for i in range(10)]
  115. [i+1 for i in range(10) if i > 5]
  116. [i+j for i in range(10) for j in range(10)]
  117. ```
  118. ### Lambda
  119. ```
  120. lambda <arg1>, <arg2>: <return value>
  121. lambda: <return value>
  122. ```
  123. Class
  124. -----
  125. ### Class
  126. ```
  127. class <name>:
  128. def __init__(self, <arg>):
  129. self.a = <arg>
  130. def __repr__(self):
  131. return str({'a': self.a})
  132. def __str__(self):
  133. return str(self.a)
  134. ```
  135. ### Enum
  136. ----
  137. ```
  138. import enum
  139. class <name>(enum.Enum):
  140. <value> = <index>
  141. ```
  142. ### Copy
  143. ```
  144. import copy
  145. copy.copy(<object>)
  146. copy.deepcopy(<object>)
  147. ```
  148. System
  149. ------
  150. ### Arguments
  151. ```
  152. import sys
  153. sys.argv
  154. ```
  155. ### Read File
  156. ```
  157. with open(<filename>, encoding='utf-8') as file:
  158. return file.readlines()
  159. ```
  160. ### Write to File
  161. ```
  162. with open(<filename>, 'w', enconding='utf-8') as file:
  163. file.write(<text>)
  164. ```
  165. ### Execute Command
  166. ```
  167. import os
  168. os.popen(<command>).read()
  169. ```
  170. JSON
  171. ----
  172. ```
  173. import json
  174. ```
  175. ### Read File
  176. ```
  177. with open(<filename>, encoding='utf-8') as file:
  178. return json.load(file)
  179. ```
  180. ### Write to File
  181. ```
  182. with open(<filename>, 'w', enconding='utf-8') as file:
  183. file.write(json.dumps(<object>))
  184. ```
  185. SQLite
  186. ------
  187. ```
  188. import sqlite3
  189. db = sqlite3.connect(<filename>)
  190. ```
  191. ### Read
  192. ```
  193. cursor = db.execute(<query>)
  194. if cursor:
  195. cursor.<fetchone/fetchall>()
  196. db.close()
  197. ```
  198. ### Write
  199. ```
  200. db.execute(<query>)
  201. db.commit()
  202. ```
  203. Threading
  204. ---------
  205. ```
  206. import threading
  207. ```
  208. ### Thread
  209. ```
  210. thread = threading.Thread(target=<function>, args=(<first arg>, ))
  211. thread.start()
  212. thread.join()
  213. ```
  214. ### Lock
  215. ```
  216. lock = threading.Rlock()
  217. lock.acquire()
  218. lock.release()
  219. ```