OSDN Git Service

Regular updates
[twpd/master.git] / python.md
index 0ef2df6..8750057 100644 (file)
--- a/python.md
+++ b/python.md
@@ -3,12 +3,17 @@ title: Python
 category: Python
 ---
 
-### Lists
+### Tuples (immutable)
+
+    tuple = ()
+
+### Lists (mutable)
 
     list = []
     list[i:j]  # returns list subset
     list[-1]   # returns last element
     list[:-1]  # returns all but the last element
+    *list      # expands all elements in place
     
     list[i] = val
     list[i:j] = otherlist  # replace ith to jth-1 elements with otherlist
@@ -34,12 +39,14 @@ category: Python
 
 ### Dict
 
+    dict = {}
     dict.keys()
     dict.values()
     "key" in dict    # let's say this returns False, then...
     dict["key"]      # ...this raises KeyError
     dict.get("key")  # ...this returns None
     dict.setdefault("key", 1)
+    **dict           # expands all k/v pairs in place
 
 ### Iteration
 
@@ -58,7 +65,7 @@ category: Python
     string.replace("-", " ")
     ",".join(list)
     "hi {0}".format('j')
-    "hi {name}" # same as "hi {}".format('name')
+    f"hi {name}" # same as "hi {}".format('name')
     str.find(",")
     str.index(",")   # same, but raises IndexError
     str.count(",")
@@ -73,6 +80,18 @@ category: Python
     str.strip()
 
     str.islower()
+    
+    /* escape characters */
+    >>> 'doesn\'t'  # use \' to escape the single quote...
+        "doesn't"
+    >>> "doesn't"  # ...or use double quotes instead
+        "doesn't"
+    >>> '"Yes," they said.'
+        '"Yes," they said.'
+    >>> "\"Yes,\" they said."
+        '"Yes," they said.'
+    >>> '"Isn\'t," they said.'
+        '"Isn\'t," they said.'
 
 ### Casting
 
@@ -109,16 +128,19 @@ category: Python
 ```py
 file = open("hello.txt", "r") # open in read mode 'r'
 file.close() 
+```
 
-print(file.read())  # read the file 
-print fh.readline() # Reading line by line
+```py
+print(file.read())  # read the entire file and set the cursor at the end of file
+print file.readline() # Reading one line
+file.seek(0, 0) # place the cursor at the beginning of the file
 ```
 
 ### Writing (overwrite)
 
 ```py
 file = open("hello.txt", "w") # open in write mode 'w'
-write("Hello World")
+file.write("Hello World") 
 
 text_lines = ["First line", "Second line", "Last line"] 
 file.writelines(text_lines)
@@ -130,7 +152,7 @@ file.close()
 
 ```py
 file = open("Hello.txt", "a") # open in append mode
-write("Hello World again")  
+file.write("Hello World again")  
 file.close()
 ```
 
@@ -138,8 +160,8 @@ file.close()
 
 ```py
 with open("welcome.txt", "r") as file:
-    # 'file' refers directly to the "welcome.txt"
+    # 'file' refers directly to "welcome.txt"
    data = file.read()
-```
 
-It closes the file automatically, no need for `file.close()`.
+# It closes the file automatically at the end of scope, no need for `file.close()`.
+```