Le module STRING, ses constantes et sa méthode format ( )
Pour plus d’infos, voir la documentation officielle : ici
Les constantes :
- ascii_letters = ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’
- ascii_lowercase = ‘abcdefghijklmnopqrstuvwxyz’
- ascii_uppercase = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
- digits = ‘0123456789’
- hexdigits = ‘0123456789abcdefABCDEF’
- octdigits = ‘01234567’
- printable = ‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTU… C’est une combinaison des digits, ascii_letters, punctuation et whitespace
- punctuation = ‘! »#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~’
- whitespace = ‘ \t\n\r\x0b\x0c’
>>> import string
>>> string.digits
'0123456789'
>>> phrase = "Je suis né le 15 août 1769"
>>> for lettre in phrase :
print (lettre, end = " ")
if lettre in string.digits :
print ("*", end = " ")
J e s u i s n é l e 1 * 5 * a o û t 1 * 7 * 6 * 9 *
>>> for lettre in phrase :
if lettre in string.digits :
print ("*", end = " ")
else :
print (lettre, end = " ")
J e s u i s n é l e * * a o û t * * * *
>>>
L’argument end= » « permet d’écrire la chaîne de caractères générée horizontalement. Sans cet argument, après chaque caractère, il y aurait passage à la ligne !
La méthode format ( )
>>> "{0},{1},{2}".format ("a","b","c")
'a,b,c'
>>> "{},{},{}".format ("a","b","c")
'a,b,c'
>>> "{2},{1},{0}".format ("a","b","c")
'c,b,a'
>>> "{0},{1},{0}".format ("abra","cad")
'abra,cad,abra'
>>> "{0}{1}{0}".format ("abra","cad")
'abracadabra'
>>> 'Coordonnées: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordonnées: 37.24N, -115.81W'
>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordonnées: {latitude}, {longitude}'.format(**coord)
'Coordonnées: 37.24N, -115.81W'
>>> prenom,nom,age = "Fabrice", "Dumont", "47"
>>> "Je m'appelle {} {} et j'ai {} ans".format (prenom,nom,age)
"Je m'appelle Fabrice Dumont et j'ai 47 ans"
>>>