[File manipulation] Context manager
with open("welcome.txt", "r") as file:
data = file.read()
[File manipulation] Writing (append)
file = open("Hello.txt", "a")
file.write("Hello World again")
file.close()
[File manipulation] Writing (overwrite)
file = open("hello.txt", "w")
file.write("Hello World")
text_lines = ["First line", "Second line", "Last line"]
file.writelines(text_lines)
file.close()
[File manipulation] Reading
file = open("hello.txt", "r")
file.close()
print(file.read())
print file.readline()
file.seek(0, 0)
Regex
import re
re.match(r'^[aeiou]', str)
re.sub(r'^[aeiou]', '?', str)
re.sub(r'(xyz)', r'\1', str)
expr = re.compile(r'^...$')
expr.match(...)
expr.sub(...)
Comprehensions
[fn(i) for i in list] # .map
map(fn, list) # .map, returns iterator
filter(fn, list) # .filter, returns iterator
[fn(i) for i in list if i > 0] # .filter.map
Casting
int(str)
float(str)
str(int)
str(float)
'string'.encode()
str[0:4]
len(str)
string.replace("-", " ")
",".join(list)
"hi {0}".format('j')
f"hi {name}" # same as "hi {}".format('name')
str.find(",")
str.index(",") # same, but raises IndexError
str.count(",")
str.split(",")
str.lower()
str.upper()
str.title()
str.lstrip()
str.rstrip()
str.strip()
str.islower()
>>> '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.'
Iteration
for item in ["a", "b", "c"]:
for i in range(4): # 0 to 3
for i in range(4, 8): # 4 to 7
for i in range(1, 9, 2): # 1, 3, 5, 7
for key, val in dict.items():
for index, item in enumerate(list):
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)
Reference