• f-string
  • := Walrus Operator

f-string

1
2
3
4
5
6
7
8
9
name = 'Celine'
score = 123.4567

def plus(x)
return score + x

print(f'name = {name}, score = {score:.3f}') # python 3.6+
print(f'{name = }, {score = :.3f}') #python 3.8+
print(f'{score = }, {plus(100) = }')

I usually use the first one, just found the new feature in after 3.8.

:=

:= Assignment Expressions (after 3.8)

scenario 1: local variable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
a = [0] * 11

# call len(a) twice
if len(a) > 10:
print(f'list too long, {len(a)} elements')

# call len(a) once
n = len(a)
if n > 10:
print(f'list too long, {n} elements')

# call len(a) once and assign it to x
# needs parenthesis, := piority lower than other operator
if (x := len(a)) > 10:
print(f'list too long, {x} elements')
print(f'list too long, {x} elements')

scanrio 2: while loop

read a string flow till the end.

1
2
3
4
5
6
7
8
9
10
11
# basic
f1 = io.StringIO('123456789')
x1 = f1.read(2)
while x1:
print(x1)
x1 = f1.read(2)

# better
f2 = io.StringIO('123456789')
while (x2 := f2.read(2)) != '':
print(x2)

scenario 3: in list comprehension

1
2
3
4
5
6
7
8
9
10
11
targets = ['apple', 'banana', 'orange']
my = ['Apple', 'Orange', 'Melon']

# print all element in my list match in target list
# call lower() twice
l1 = [f.lower() for f in my if f.lower() in targets]
print(l1)

# call lower() once
l2 = [f for fruit in my if (f:= fruit.lower()) in targets]
print(l2)