Python Cheatsheet
December 22, 2024 · 1 min read · Page View:
If you have any questions, feel free to comment below.
Basic Data Types #
bin(16) oct(16) hex(16)
int(a, 2) int(b, 8) int(c, 16)
round(a, 1)
pow(x,n)
- Forward indexing - starts incrementing from 0, and a space is also a position.
- Backward indexing - starts decrementing from -1, and a space is also a position.
variable[start🔚step]
when the step is -1, which means the previous position is greater than the latter position by -1.
String #
.split(" ")
",".join(str)
.strip(the character to be removed)
.replace("to be replaced","replace")
.count("str")
.upper() .lower() .title()
any()
all()
type()
isinstance(var, type)
str(num)
int()
float()
eval()
List #
variable[start🔚step]
use +
to concatenate lists
use *
to duplicate lists
.append(element)
.extend(list)
.insert(position, element)
.remove(element)
default is the first element meeting the condition.pop(position)
default is the last.clear()
empty the list.index(element)
return its index.count(element)
.reverse()
in-place reverse, no return value.copy()
shallow copy ==[:]
.sort()
in-place sort, no return value.list.sort(reverse = True)
sorted(列表)
temporary sort, original list remains unchanged.sorted(列表, reverse = True)
Tuple #
def f1(x): return x2, x3 # packing
a, b = f1(3) unpacking zip() packing
Dictionary #
- unordered
- key must be immutable
dict[key]
variable[new key] = new value
del variable[key]
.keys()
return the list of keys.values()
return the list of values.items()
return the list of key-value pairs.get(key, default)
get the value of the key, if the key does not exist, return the default value.update(dict)
update the dictionary, if the key does not exist, add it.pop(key)
delete the value of the key.clear()
clear the dictionary.copy()
shallow copy
Set #
- unordered, which means the pop is invalid
- element must be immutable
.add(element)
.remove(element)
.clear()
.copy()
S & T
intersectionS | T
unionS - T
differenceS ^ T
XOR
Related readings
- Python Function Parameter
- Python Control Structure
- Python Composite Data Type
- Python Basic Data Type
- Python Basic Syntax Elements
If you find this blog useful and want to support my blog, need my skill for something, or have a coffee chat with me, feel free to: