Toolbending:Python solutions
Itérations
Motifs
<syntaxhighlight lang="python"> lines = 7 character = "+"
i = 1
while i <= lines: print character*i i = i + 1 </syntaxhighlight>
Renversement
<syntaxhighlight lang="python"> words = ("I", "LOVE", "YOU")
i = len(words)
for word in words: print words[i-1], i = i - 1 </syntaxhighlight>
Les données alphanumériques
Recherche d'un caractère particulier dans une chaîne
<syntaxhighlight lang="python">
- !/usr/bin/env python
- -*- coding: utf-8 -*-
- Chaîne fournie au départ :
ch = "I will always love you"
- Caractère à rechercher :
cr = "a"
- Recherche proprement dite :
lc = len(ch)
- nombre de caractères à tester
i = 0
- indice du caractère en cours d'examen
t = 0
- "drapeau" à lever si le caractère recherché est présent
while i < lc: if ch[i] == cr: t = 1 i = i + 1
- Affichage :
print "Le caractère", cr, if t == 1: print "est présent", else: print "est inrouvable", print "dans la chaîne", ch </syntaxhighlight>
Insertion d'un caractère d'espacement dans une chaîne
<syntaxhighlight lang="python">
- !/usr/bin/env python
- -*- coding: utf-8 -*-
- Chaîne fournie au départ :
ch = "amour"
- Caractère à insérer:
ci = u"\u2665"
- Le nombre de caractères à insérer est inférieur d'une unité au nombre de caractères de la chaîne. On traitera donc celle-ci à partir de son second caractère (en omettant le premier).
lc = len(ch) # nombre de caractères total i = 1 # indice du premier caractère à examiner (le second, en fait) nch = ch[0] # nouvelle chaîne à construire (contient déjà le premier car.) while i < lc: nch = nch + ci + ch[i] i = i + 1
- Affichage
print nch </syntaxhighlight>
Inversion d'une chaîne de caractères
<syntaxhighlight lang="python">
- !/usr/bin/env python
- -*- coding: utf-8 -*-
- Chaîne fournie au départ :
ch = u"déclarations" lc = len(ch) # nombre de caractères total i = lc - 1 # le traitement commencera à partir du dernier caractère nch = "" # nouvelle chaîne à construire (vide au départ)
while i >= 0:
nch = nch + ch[i] i = i - 1
- Affichage :
print nch </syntaxhighlight>