123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209 |
- <!doctype html>
- <html lang=fr>
- <head>
- <!-- Always define the charset before the title -->
- <meta charset=utf-8>
- <title>Formatage des chaînes de caractères en Python — Biologeek — David Larlet</title>
- <!-- Define a viewport to mobile devices to use - telling the browser to assume that the page is as wide as the device (width=device-width) and setting the initial page zoom level to be 1 (initial-scale=1.0) -->
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <!-- Fake favicon, to avoid extra request to the server -->
- <link rel="icon" href="data:;base64,iVBORw0KGgo=">
- <link type="application/atom+xml" rel="alternate" title="Feed" href="/david/log/" />
- <link rel="manifest" href="/manifest.json">
-
- <link rel="stylesheet" href="/static/david/css/larlet-david-_J6Rv.css" data-instant-track />
-
- <noscript>
- <style type="text/css">
- /* Otherwise fonts are loaded by JS for faster initial rendering. See scripts at the bottom. */
- body {
- font-family: 'EquityTextB', serif;
- }
- h1, h2, h3, h4, h5, h6, time, nav a, nav a:link, nav a:visited {
- font-family: 'EquityCapsB', sans-serif;
- font-variant: normal;
- }
- </style>
- </noscript>
-
- <!-- Canonical URL for SEO purposes -->
- <link rel="canonical" href="https://larlet.fr/david/biologeek/archives/20060121-formatage-des-chaines-de-caracteres-en-python">
-
- </head>
- <body>
- <div>
-
- <header>
- <nav>
- <p>
- <small>
- Je suis <a href="/david/" title="Profil public">David Larlet</a>, <a href="/david/pro/" title="Activité professionnelle">artisan</a> du web qui vous <a href="/david/pro/accompagnement/" title="Activité d’accompagnement">accompagne</a><span class="more-infos"> dans l’acquisition de savoirs pour concevoir des <a href="/david/pro/produits-essentiels/" title="Qu’est-ce qu’un produit essentiel ?">produits essentiels</a></span>. <span class="more-more-infos">Discutons ensemble d’une <a href="/david/pro/devis/" title="En savoir plus">non-demande de devis</a>.</span> Je partage ici mes <a href="/david/blog/" title="Expériences bienveillantes">réflexions</a> et <a href="/david/correspondances/2017/" title="Lettres hebdomadaires">correspondances</a>.
- </small>
- </p>
- </nav>
- </header>
-
-
- <section>
- <h1 property="schema:name">Formatage des chaînes de caractères en Python</h1>
- <article typeof="schema:BlogPosting">
- <div property="schema:articleBody">
- <img src="/static/david/biologeek/images/logos/bonnes_pratiques_python.png" alt="vignette" style="float:left; margin: 0.5em 1em;" property="schema:thumbnailUrl" />
- <p>À l'intersection entre bonnes pratiques et optimisation comment afficher des chaînes de caractère en Python ? Privillégier la lisibilité ou l'optimisation ? Les deux mon capitaine !</p>
-
- <p>Il existe deux méthodes assez classiques en Python pour formater des chaînes de caractère, à partir de <strong>signes plus (+)</strong> ou de <strong>%s</strong>. Considérons les chaînes de caractères suivantes :</p>
-
- <pre>title = "optimisation" * 1000
- cat = "python" * 1000
- main_title = "biologeek" * 1000</pre>
-
- <p>Si l'on utilise des <strong>signes plus (+)</strong> :</p>
-
- <pre>def foo1():
- page = ""
- for x in range(500):
- page += "<title>" + title + " - " + cat + " - " + main_title + "</title>"
- return page</pre>
-
- <p>Cette fonction s'exécute en <strong>5,91 secondes</strong>, si l'on utilise des <strong>%s</strong> :</p>
-
- <pre>def foo2():
- page = ""
- for x in range(500):
- page += "<title>%s - %s - %s</title>" % (title, cat, main_title)
- return page</pre>
-
- <p>Elle s'exécute dans le même temps. À choisir, beaucoup préfèrent la seconde (notamment en raison du lourd héritage d'autre langages préhistoriques...) mais heureusement il existe en python un moyen de faire encore plus lisible : utiliser des dictionnaires.</p>
-
- <pre>def foo3():
- dic = {
- "title" : title,
- "cat" : cat,
- "main_title" : main_title
- }
- page = ""
- for x in range(500):
- page += "<title>%(title)s - %(cat)s - %(main_title)s</title>" % dic
- return page</pre>
-
- <p>Le temps d'exécution est ici aussi identique et si vous ne voulez pas créer de dictionnaire supplémentaire, il est possible de mettre directement le dictionnaire en argument :</p>
-
- <pre>page += "<title>%(title)s - %(cat)s - %(main_title)s</title>" %\
- {"title":title, "cat":cat, "main_title":main_title}</pre>
-
- <p>Enfin il existe une dernière méthode utilisant les fonctions intégrées (pour en savoir plus, je vous renvoie sur l'excellent <a href="http://diveintopython.adrahon.org/html_processing/locals_and_globals.html">Dive into Python</a>).</p>
-
- <pre>def foo4():
- title = "optimisation" * 1000
- cat = "python" * 1000
- main_title = "biologeek" * 1000
- page = ""
- for x in range(500):
- page += "<title>%(title)s - %(cat)s - %(main_title)s</title>" % locals()
- return page</pre>
-
- <p>Mais elle met <strong>6,07 secondes</strong> à s'exécuter et ce temps augmente avec le nombre de variables locales donc c'est moins performant... mais tellement pratique :-).</p>
-
- <p>Conclusion, si vous voulez concilier les deux, à savoir optimisation et lisibilité, je vous conseille d'utiliser des dictionnaires pour formater vos chaînes de caractères et si vous n'avez pas nécessairement besoin d'aller vite <strong>locals()</strong> se révèle être très pratique (encore une fois faites des tests !).</p>
-
- <p>Je vous rappelle qu'un billet récapitule l'ensemble des <a href="https://larlet.fr/david/biologeek/archives/20060121-bonnes-pratiques-de-la-programmation-en-python/">bonnes pratiques et optimisations en Python</a>.</p>
- </div>
- </article>
- <footer>
- <h6 property="schema:datePublished">— 21/01/2006</h6>
- </footer>
- </section>
- <section>
- <div>
- <h3>Articles peut-être en rapport</h3>
- <ul>
- <li><a href="/david/biologeek/archives/20080511-bonnes-pratiques-et-astuces-python/" title="Accès à Bonnes pratiques et astuces Python">Bonnes pratiques et astuces Python</a></li>
- <li><a href="/david/biologeek/archives/20061025-benchmarks-map-filter-vs-list-comprehensions/" title="Accès à Benchmarks map, filter vs. list-comprehensions">Benchmarks map, filter vs. list-comprehensions</a></li>
- <li><a href="/david/biologeek/archives/20060425-python-et-underscore/" title="Accès à Python : lisibilité vs simplicité">Python : lisibilité vs simplicité</a></li>
- </ul>
- </div>
- </section>
- <section>
- <div id="comments">
- <h3>Commentaires</h3>
-
- <div class="comment" typeof="schema:UserComments">
- <p class="comment-meta">
- <span class="comment-author" property="schema:creator">szdavid</span> le <span class="comment-date" property="schema:commentTime">22/01/2006</span> :
- </p>
- <div class="comment-content" property="schema:commentText">
- <p>Intéressant...<br />
- <br />
- Bon, là, j'utilise les %s ; la notion de l'utilisation des dictionnaires semble intéressante...<br />
- <br />
- C'est incompatble avec mes développements actuels mais je vais regarder ça de plus près</p>
- </div>
- </div>
- <div class="comment" typeof="schema:UserComments">
- <p class="comment-meta">
- <span class="comment-author" property="schema:creator">Olivier</span> le <span class="comment-date" property="schema:commentTime">23/01/2006</span> :
- </p>
- <div class="comment-content" property="schema:commentText">
- <p>Elle est énorme la méthode avec dico !<br />
- J'achète ;)<br />
- <br />
- Je ne trouve pas contre pas la première méthode si illisible que ça, franchement la seconde est bien plus difficile à lire lorsqu'on commence à avoir un nombre conséquent de variables.</p>
- </div>
- </div>
- <div class="comment" typeof="schema:UserComments">
- <p class="comment-meta">
- <span class="comment-author" property="schema:creator">David, biologeek</span> le <span class="comment-date" property="schema:commentTime">23/01/2006</span> :
- </p>
- <div class="comment-content" property="schema:commentText">
- <p>Oui, en fait ça dépend aussi beaucoup des habitudes de programmation et des langages connus.<br />
- Je corrige mon billet en conséquence.</p>
- </div>
- </div>
- <div class="comment" typeof="schema:UserComments">
- <p class="comment-meta">
- <span class="comment-author" property="schema:creator">littletux</span> le <span class="comment-date" property="schema:commentTime">04/02/2006</span> :
- </p>
- <div class="comment-content" property="schema:commentText">
- <p>ATTENTION : JE SUBIS avec un S<br />
- <br />
- ÉNORMÉMENT DE SPAM ACTUELLEMENT ET J'AI DONC CONFIGURÉ DOTCLEAR POUR MODÉRER LES COMMENTAIRES A POSTERIORI<br />
- <br />
- A PRIORI ? avant diffusion d'après ce que j'ai compris.<br />
- <br />
- Mes 2 eurocents.<br />
- <br />
- PS:<br />
- Très bonne idée ce petit texte informatif, je le note !</p>
- </div>
- </div>
- <div class="comment" typeof="schema:UserComments">
- <p class="comment-meta">
- <span class="comment-author" property="schema:creator">David, biologeek</span> le <span class="comment-date" property="schema:commentTime">04/02/2006</span> :
- </p>
- <div class="comment-content" property="schema:commentText">
- <p>En effet, oups bon de toute façon ça va changer incessamment sous peu :)</p>
- </div>
- </div>
-
- </div>
- </section>
-
-
- <footer>
- <nav>
- <p>
- <small>
- Je réponds quasiment toujours aux <a href="mailto:david%40larlet.fr" title="Envoyer un email">emails</a> (<a href="/david/signature/" title="Ma signature actuelle avec possibilité de chiffrement">signés</a>) et vous pouvez me rencontrer à Montréal. <span class="more-infos">N’hésitez pas à <a href="/david/log/" title="Être tenu informé des mises à jour">vous abonner</a> pour être tenu informé des publications récentes.</span>
- </small>
- </p>
- </nav>
- </footer>
-
- </div>
-
- <script src="/static/david/js/larlet-david-3ee43f.js" data-no-instant></script>
-
- <script data-no-instant>InstantClick.init()</script>
-
- </body>
- </html>
|