Python tricks¶
format()¶
Vous pouvez spécifier un séparateur des milliers pour format() :
>>> format(123456789, ",")
'123,456,789'
>>> format(123456789, "_")
'123_456_789'
Idem pour les f-string :
>>> f"{123456789:,}"
'123,456,789'
>>> f"{123456789:_}"
'123_456_789'
pow()¶
pow() peut prendre un 3ème argument pour calculer pow(x, y) % z :
x, y, z = 123456789, 2345678, 17
# Option 1: not efficient at all
res = pow(x, y) % z # Does not end in more than 1 minute!
# Option 2: here we can talk!
res = pow(x, y, z) # Instantly
re.sub()¶
re.sub() peut être utilisée pour remplacer plusieurs caractères dans un texte (évitant ainsi d’avoir à enchaîner les appels à str.replace ou au plus coûteux str.translate) :
import re
fname = "Ça, c'est un nom de fichier (2).odt"
pattern = re.compile(r'([/:"|*<>?\\])')
fname_sanitized = re.sub(pattern, "-", fname)
Benchmark
Script :
import re
setup_1 = """
fname = "Ça, c'est un nom de fichier (2).odt"
"""
stmt_1 = """\
fname.replace('/', '-')\
.replace(':', '-')\
.replace('"', '-')\
.replace('|', '-')\
.replace('*', '-')\
.replace('<', '-')\
.replace('>', '-')\
.replace('?', '-')\
.replace('\\\\', '-')
"""
setup_2 = """
from re import compile, sub
pattern = compile(r'([/:"|*<>?\\\\])')
fname = "Ça, c'est un nom de fichier (2).odt"
"""
stmt_2 = "sub(pattern, '-', fname)"
setup_3 = """
repmap = {ord(c): "-" for c in '/:"|*<>?\\\\'}
fname = "Ça, c'est un nom de fichier (2).odt"
"""
stmt_3 = "fname.translate(repmap)"
print(min(repeat(stmt_1, setup_1, number=100000)))
print(min(repeat(stmt_2, setup_2, number=100000)))
print(min(repeat(stmt_3, setup_3, number=100000)))
Résultats :
$ python3.8 bench.py
0.041965347016230226 # str.replace()
0.10586143494583666 # re.sub()
0.2713684451300651 # str.translate()
str.startswith & str.endswith¶
str.startswith et str.endswith peuvent prendre un tuple en paramètre :
text = "azerty"
# Option 1: basic usage, not efficient
if (
text.startswith("a") # noqa:PIE810
or text.startswith("b")
or text.startswith("c")
or text.startswith("d")
or text.startswith("e")
or text.startswith("f")
):
pass
# Option 2: best usage, efficient
if text.startswith(("a", "b", "c", "d", "e", "f")):
pass
Résultats du benchmark
# text = 'azerty', the 1st condition is True
Option 1: 0.171 usec
Option 2: 0.174 usec
# text = 'czerty', the last condition is True
Option 1: 0.498 usec
Option 2: 0.200 usec
# text = 'nzerty', all conditions are False
Option 1: 0.472 usec
Option 2: 0.186 usec
time & datetime¶
Vous pouvez supprimer les zéros ajoutés pour les différentes fonctions du module time qui prennent un format en entrée (valable pour datetime également) :
>>> import datetime, time
>>> today = datetime.datetime.now().timetuple()
>>> time.strftime("%Y-%m-%d", today)
'2017-12-06'
>>> time.strftime("%Y-%m-%-d", today) # Check the '%-d'
'2017-12-6'
📜 Historique¶
- 2024-02-01
Déplacement de l’article depuis le blog.
- 2019-12-13
Ajout de
re.sub().- 2019-04-19
Ajout de
format().- 2017-12-06
Ajout de
time&datetime.- 2017-10-09
Premier jet avec
str.startswith()&str.endswith()etpow(), il vaut mieux publier maintenant que jamais ☺