An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
July 16, 2020 04:53 am GMT
Original Link: https://dev.to/lamhoanganh/python-cheat-sheet-2pbn
Python Cheat Sheet
This cheat sheet tries to provide a basic reference for beginner and advanced developers, lower the entry barrier for newcomers, and help veterans refresh the old tricks. Full Python Cheat Sheet.
Lists
list = []list[i:j] # returns list subsetlist[-1] # returns last elementlist[:-1] # returns all but the last elementlist[i] = vallist[i:j] = otherlist # replace ith to jth-1 elements with otherlistdel list[i:j]list.append(item)list.extend(another_list)list.insert(index, item)list.pop() # returns and removes last element from the listlist.pop(i) # returns and removes i-th element from the listlist.remove(i) # removes the first item from the list whose value is ilist1 + list2 # combine two list set(list) # remove duplicate elements from a listlist.reverse() # reverses the elements of the list in-placelist.count(item)sum(list)zip(list1, list2) # returns list of tuples with n-th element of both list1 and list2list.sort() # sorts in-place, returns Nonesorted(list) # returns sorted copy of list",".join(list) # returns a string with list elements seperated by comma
Dict
dict.keys()dict.values()"key" in dict # let's say this returns False, then...dict["key"] # ...this raises KeyErrordict.get("key") # ...this returns Nonedict.setdefault("key", 1)
Iteration
for item in ["a", "b", "c"]:for i in range(4): # 0 to 3for i in range(4, 8): # 4 to 7for i in range(1, 9, 2): # 1, 3, 5, 7for key, val in dict.items():for index, item in enumerate(list):
String
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 IndexErrorstr.count(",")str.split(",")str.lower()str.upper()str.title()str.lstrip()str.rstrip()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
int(str)float(str)str(int)str(float)'string'.encode()
Comprehensions
[fn(i) for i in list] # .mapmap(fn, list) # .map, returns iteratorfilter(fn, list) # .filter, returns iterator[fn(i) for i in list if i > 0] # .filter.map
Regex
import rere.match(r'^[aeiou]', str)re.sub(r'^[aeiou]', '?', str)re.sub(r'(xyz)', r'\1', str)expr = re.compile(r'^...$')expr.match(...)expr.sub(...)
File manipulation
Reading
file = open("hello.txt", "r") # open in read mode 'r'file.close()
print(file.read()) # read the entire file and set the cursor at the end of fileprint file.readline() # Reading one linefile.seek(0, 0) # place the cursor at the beggining of the file
Writing (overwrite)
file = open("hello.txt", "w") # open in write mode 'w'file.write("Hello World") text_lines = ["First line", "Second line", "Last line"] file.writelines(text_lines)file.close()
Writing (append)
file = open("Hello.txt", "a") # open in append modefile.write("Hello World again") file.close()
Context manager
with open("welcome.txt", "r") as file: # 'file' refers directly to "welcome.txt" data = file.read()# It closes the file automatically at the end of scope, no need for `file.close()`.
Original Link: https://dev.to/lamhoanganh/python-cheat-sheet-2pbn
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To