1
0
mirror of https://github.com/onkelbeh/cheatsheets.git synced 2026-08-15 21:44:51 +02:00

Add missing syntax highlighting to python.md (#2154)

Fixes missing code highlighting in half of the Python code snippets.

The top half of the page had code examples formatted as code blocks with
4 space character indentations and no syntax highlighting as a result.

The bottom half on the other hand, used code blocks surrounded by
"```py" formatting brackets which hints to many markdown renders that
syntax highlighting should be applied.

This unifies the code blocks in the top half of the page to use the same
formatting syntax used in the bottom half with syntax highlighting.

This change was prompted by requests to add the syntax highlighting in
comments on the https://devhints.io/python page.
This commit is contained in:
David Lakin
2024-07-16 08:32:46 -04:00
committed by GitHub
parent edfb8bba78
commit 27970b1495

187
python.md
View File

@@ -5,121 +5,138 @@ category: Python
### Tuples (immutable) ### Tuples (immutable)
tuple = () ```py
tuple = ()
```
### Lists (mutable) ### Lists (mutable)
list = [] ```py
list[i:j] # returns list subset list = []
list[-1] # returns last element list[i:j] # returns list subset
list[:-1] # returns all but the last element list[-1] # returns last element
*list # expands all elements in place 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
del list[i:j]
list.append(item) list[i] = val
list.extend(another_list) list[i:j] = otherlist # replace ith to jth-1 elements with otherlist
list.insert(index, item) del list[i:j]
list.pop() # returns and removes last element from the list
list.pop(i) # returns and removes i-th element from the list
list.remove(i) # removes the first item from the list whose value is i
list1 + list2 # combine two list
set(list) # remove duplicate elements from a list
list.reverse() # reverses the elements of the list in-place list.append(item)
list.count(item) list.extend(another_list)
sum(list) list.insert(index, item)
list.pop() # returns and removes last element from the list
list.pop(i) # returns and removes i-th element from the list
list.remove(i) # removes the first item from the list whose value is i
list1 + list2 # combine two list
set(list) # remove duplicate elements from a list
zip(list1, list2) # returns list of tuples with n-th element of both list1 and list2 list.reverse() # reverses the elements of the list in-place
list.sort() # sorts in-place, returns None list.count(item)
sorted(list) # returns sorted copy of list sum(list)
",".join(list) # returns a string with list elements seperated by comma
zip(list1, list2) # returns list of tuples with n-th element of both list1 and list2
list.sort() # sorts in-place, returns None
sorted(list) # returns sorted copy of list
",".join(list) # returns a string with list elements separated by comma
```
### Dict ### Dict
dict = {} ```py
dict.keys() dict = {}
dict.values() dict.keys()
"key" in dict # let's say this returns False, then... dict.values()
dict["key"] # ...this raises KeyError "key" in dict # let's say this returns False, then...
dict.get("key") # ...this returns None dict["key"] # ...this raises KeyError
dict.setdefault("key", 1) dict.get("key") # ...this returns None
**dict # expands all k/v pairs in place dict.setdefault("key", 1)
**dict # expands all k/v pairs in place
```
### Iteration ### Iteration
for item in ["a", "b", "c"]: ```py
for i in range(4): # 0 to 3 for item in ["a", "b", "c"]:
for i in range(4, 8): # 4 to 7 for i in range(4): # 0 to 3
for i in range(1, 9, 2): # 1, 3, 5, 7 for i in range(4, 8): # 4 to 7
for key, val in dict.items(): for i in range(1, 9, 2): # 1, 3, 5, 7
for index, item in enumerate(list): for key, val in dict.items():
for index, item in enumerate(list):
```
### [String](https://docs.python.org/2/library/stdtypes.html#string-methods) ### [String](https://docs.python.org/2/library/stdtypes.html#string-methods)
str[0:4] ```py
len(str) str[0:4]
len(str)
string.replace("-", " ") string.replace("-", " ")
",".join(list) ",".join(list)
"hi {0}".format('j') "hi {0}".format('j')
f"hi {name}" # same as "hi {}".format('name') f"hi {name}" # same as "hi {}".format('name')
str.find(",") str.find(",")
str.index(",") # same, but raises IndexError str.index(",") # same, but raises IndexError
str.count(",") str.count(",")
str.split(",") str.split(",")
str.lower() str.lower()
str.upper() str.upper()
str.title() str.title()
str.lstrip() str.lstrip()
str.rstrip() str.rstrip()
str.strip() str.strip()
str.islower() str.islower()
/* escape characters */ /* escape characters */
>>> 'doesn\'t' # use \' to escape the single quote... >>> 'doesn\'t' # use \' to escape the single quote...
"doesn't" "doesn't"
>>> "doesn't" # ...or use double quotes instead >>> "doesn't" # ...or use double quotes instead
"doesn't" "doesn't"
>>> '"Yes," they said.' >>> '"Yes," they said.'
'"Yes," they said.' '"Yes," they said.'
>>> "\"Yes,\" they said." >>> "\"Yes,\" they said."
'"Yes," they said.' '"Yes," they said.'
>>> '"Isn\'t," they said.' >>> '"Isn\'t," they said.'
'"Isn\'t," they said.' '"Isn\'t," they said.'
```
### Casting ### Casting
int(str) ```py
float(str) int(str)
str(int) float(str)
str(float) str(int)
'string'.encode() str(float)
'string'.encode()
```
### Comprehensions ### Comprehensions
[fn(i) for i in list] # .map ```py
map(fn, list) # .map, returns iterator [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 filter(fn, list) # .filter, returns iterator
[fn(i) for i in list if i > 0] # .filter.map
```
### Regex ### Regex
import re ```py
import re
re.match(r'^[aeiou]', str) re.match(r'^[aeiou]', str)
re.sub(r'^[aeiou]', '?', str) re.sub(r'^[aeiou]', '?', str)
re.sub(r'(xyz)', r'\1', str) re.sub(r'(xyz)', r'\1', str)
expr = re.compile(r'^...$') expr = re.compile(r'^...$')
expr.match(...) expr.match(...)
expr.sub(...) expr.sub(...)
```
## File manipulation ## File manipulation