Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.html 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. <!doctype html>
  2. <html lang=fr>
  3. <head>
  4. <!-- Always define the charset before the title -->
  5. <meta charset=utf-8>
  6. <title>Formatage des chaînes de caractères en Python — Biologeek — David Larlet</title>
  7. <!-- 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) -->
  8. <meta name="viewport" content="width=device-width, initial-scale=1"/>
  9. <!-- Fake favicon, to avoid extra request to the server -->
  10. <link rel="icon" href="data:;base64,iVBORw0KGgo=">
  11. <link type="application/atom+xml" rel="alternate" title="Feed" href="/david/log/" />
  12. <link rel="manifest" href="/manifest.json">
  13. <link rel="stylesheet" href="/static/david/css/larlet-david-_J6Rv.css" data-instant-track />
  14. <noscript>
  15. <style type="text/css">
  16. /* Otherwise fonts are loaded by JS for faster initial rendering. See scripts at the bottom. */
  17. body {
  18. font-family: 'EquityTextB', serif;
  19. }
  20. h1, h2, h3, h4, h5, h6, time, nav a, nav a:link, nav a:visited {
  21. font-family: 'EquityCapsB', sans-serif;
  22. font-variant: normal;
  23. }
  24. </style>
  25. </noscript>
  26. <!-- Canonical URL for SEO purposes -->
  27. <link rel="canonical" href="https://larlet.fr/david/biologeek/archives/20060121-formatage-des-chaines-de-caracteres-en-python">
  28. </head>
  29. <body>
  30. <div>
  31. <header>
  32. <nav>
  33. <p>
  34. <small>
  35. 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>.
  36. </small>
  37. </p>
  38. </nav>
  39. </header>
  40. <section>
  41. <h1 property="schema:name">Formatage des chaînes de caractères en Python</h1>
  42. <article typeof="schema:BlogPosting">
  43. <div property="schema:articleBody">
  44. <img src="/static/david/biologeek/images/logos/bonnes_pratiques_python.png" alt="vignette" style="float:left; margin: 0.5em 1em;" property="schema:thumbnailUrl" />
  45. <p>À l'intersection entre bonnes pratiques et optimisation comment afficher des chaînes de caractère en Python&nbsp;? Privillégier la lisibilité ou l'optimisation&nbsp;? Les deux mon capitaine&nbsp;!</p>
  46. <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&nbsp;:</p>
  47. <pre>title = "optimisation" * 1000
  48. cat = "python" * 1000
  49. main_title = "biologeek" * 1000</pre>
  50. <p>Si l'on utilise des <strong>signes plus (+)</strong>&nbsp;:</p>
  51. <pre>def foo1():
  52. page = ""
  53. for x in range(500):
  54. page += "&lt;title&gt;" + title + " - " + cat + " - " + main_title + "&lt;/title&gt;"
  55. return page</pre>
  56. <p>Cette fonction s'exécute en <strong>5,91 secondes</strong>, si l'on utilise des <strong>%s</strong>&nbsp;:</p>
  57. <pre>def foo2():
  58. page = ""
  59. for x in range(500):
  60. page += "&lt;title&gt;%s - %s - %s&lt;/title&gt;" % (title, cat, main_title)
  61. return page</pre>
  62. <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&nbsp;: utiliser des dictionnaires.</p>
  63. <pre>def foo3():
  64. dic = {
  65. "title" : title,
  66. "cat" : cat,
  67. "main_title" : main_title
  68. }
  69. page = ""
  70. for x in range(500):
  71. page += "&lt;title&gt;%(title)s - %(cat)s - %(main_title)s&lt;/title&gt;" % dic
  72. return page</pre>
  73. <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&nbsp;:</p>
  74. <pre>page += "&lt;title&gt;%(title)s - %(cat)s - %(main_title)s&lt;/title&gt;" %\
  75. {"title":title, "cat":cat, "main_title":main_title}</pre>
  76. <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>
  77. <pre>def foo4():
  78. title = "optimisation" * 1000
  79. cat = "python" * 1000
  80. main_title = "biologeek" * 1000
  81. page = ""
  82. for x in range(500):
  83. page += "&lt;title&gt;%(title)s - %(cat)s - %(main_title)s&lt;/title&gt;" % locals()
  84. return page</pre>
  85. <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>
  86. <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>
  87. <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>
  88. </div>
  89. </article>
  90. <footer>
  91. <h6 property="schema:datePublished">— 21/01/2006</h6>
  92. </footer>
  93. </section>
  94. <section>
  95. <div>
  96. <h3>Articles peut-être en rapport</h3>
  97. <ul>
  98. <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>
  99. <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>
  100. <li><a href="/david/biologeek/archives/20060425-python-et-underscore/" title="Accès à Python : lisibilité vs simplicité">Python : lisibilité vs simplicité</a></li>
  101. </ul>
  102. </div>
  103. </section>
  104. <section>
  105. <div id="comments">
  106. <h3>Commentaires</h3>
  107. <div class="comment" typeof="schema:UserComments">
  108. <p class="comment-meta">
  109. <span class="comment-author" property="schema:creator">szdavid</span> le <span class="comment-date" property="schema:commentTime">22/01/2006</span> :
  110. </p>
  111. <div class="comment-content" property="schema:commentText">
  112. <p>Intéressant...<br />
  113. <br />
  114. Bon, là, j'utilise les %s ; la notion de l'utilisation des dictionnaires semble intéressante...<br />
  115. <br />
  116. C'est incompatble avec mes développements actuels mais je vais regarder ça de plus près</p>
  117. </div>
  118. </div>
  119. <div class="comment" typeof="schema:UserComments">
  120. <p class="comment-meta">
  121. <span class="comment-author" property="schema:creator">Olivier</span> le <span class="comment-date" property="schema:commentTime">23/01/2006</span> :
  122. </p>
  123. <div class="comment-content" property="schema:commentText">
  124. <p>Elle est énorme la méthode avec dico !<br />
  125. J'achète ;)<br />
  126. <br />
  127. 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>
  128. </div>
  129. </div>
  130. <div class="comment" typeof="schema:UserComments">
  131. <p class="comment-meta">
  132. <span class="comment-author" property="schema:creator">David, biologeek</span> le <span class="comment-date" property="schema:commentTime">23/01/2006</span> :
  133. </p>
  134. <div class="comment-content" property="schema:commentText">
  135. <p>Oui, en fait ça dépend aussi beaucoup des habitudes de programmation et des langages connus.<br />
  136. Je corrige mon billet en conséquence.</p>
  137. </div>
  138. </div>
  139. <div class="comment" typeof="schema:UserComments">
  140. <p class="comment-meta">
  141. <span class="comment-author" property="schema:creator">littletux</span> le <span class="comment-date" property="schema:commentTime">04/02/2006</span> :
  142. </p>
  143. <div class="comment-content" property="schema:commentText">
  144. <p>ATTENTION : JE SUBIS avec un S<br />
  145. <br />
  146. ÉNORMÉMENT DE SPAM ACTUELLEMENT ET J'AI DONC CONFIGURÉ DOTCLEAR POUR MODÉRER LES COMMENTAIRES A POSTERIORI<br />
  147. <br />
  148. A PRIORI ? avant diffusion d'après ce que j'ai compris.<br />
  149. <br />
  150. Mes 2 eurocents.<br />
  151. <br />
  152. PS:<br />
  153. Très bonne idée ce petit texte informatif, je le note !</p>
  154. </div>
  155. </div>
  156. <div class="comment" typeof="schema:UserComments">
  157. <p class="comment-meta">
  158. <span class="comment-author" property="schema:creator">David, biologeek</span> le <span class="comment-date" property="schema:commentTime">04/02/2006</span> :
  159. </p>
  160. <div class="comment-content" property="schema:commentText">
  161. <p>En effet, oups bon de toute façon ça va changer incessamment sous peu :)</p>
  162. </div>
  163. </div>
  164. </div>
  165. </section>
  166. <footer>
  167. <nav>
  168. <p>
  169. <small>
  170. Je réponds quasiment toujours aux <a href="m&#x61;ilto:d&#x61;vid%40l&#x61;rlet&#46;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>
  171. </small>
  172. </p>
  173. </nav>
  174. </footer>
  175. </div>
  176. <script src="/static/david/js/larlet-david-3ee43f.js" data-no-instant></script>
  177. <script data-no-instant>InstantClick.init()</script>
  178. </body>
  179. </html>