Python — Chaînes de caractères et dictionnaires
1) Syntaxe des chaînes
On peut définir des chaînes avec quotes simples ou doubles (équivalentes) :
x = 'Pluto is a planet'
y = "Pluto is a planet"
print(x == y)
Sortie
True
Pratique : utilisez des doubles quotes si la chaîne contient une apostrophe, et inversement.
print("Pluto's a planet!")
print('My dog is named "Pluto"')
Sortie
Pluto's a planet! My dog is named "Pluto"
Si vous mettez une apostrophe dans des quotes simples, Python l’interprète comme la fin de la chaîne → SyntaxError :
'Pluto's a planet!'
^
SyntaxError: invalid syntax
On échappe alors l’apostrophe avec un backslash :
print('Pluto\'s a planet!')
Sortie
Pluto's a planet!
Séquences d’échappement utiles
| Ce que vous tapez | Ce que vous obtenez | Exemple | Affichage |
|---|---|---|---|
\' | ' | 'What\'s up?' | What's up? |
\" | " | "That's \"cool\"" | That's "cool" |
\\ | \ | "Look, a mountain: /\\" | Look, a mountain: /\ |
\n | retour à la ligne | "1\n2 3" | 1 2 3 |
hello = "hello\nworld"
print(hello)
Sortie
hello world
Triple-quotes : permettent d’inclure des retours à la ligne littéraux.
triplequoted_hello = """hello
world"""
print(triplequoted_hello)
Sortie
hello world
Par défaut, print() ajoute un saut de ligne (modifiable via end=) :
print("hello")
print("world")
print("hello", end="")
print("pluto", end="")
Sortie
hello world hellopluto
2) Les chaînes sont des séquences
On peut indexer, trancher, mesurer, itérer :
planet = "Pluto"
print(planet[0]) # 'P'
print(planet[-3:]) # 'uto'
print(len(planet)) # 5
print(planet[-1]) # 'o'
print(planet[1:4]) # 'lut'
print(planet[3:]) # 'to'
print([c + "! " for c in planet])
Sortie
P uto 5 o lut to ['P! ', 'l! ', 'u! ', 't! ', 'o! ']
Mais les chaînes sont immuables :
planet = "Pluto"
# planet[0] = "B" # ❌ TypeError
Sortie
TypeError Traceback (most recent call last) /tmp/ipykernel_19/2683731249.py in <module> ----> 1 planet[0] = 'B' 2 # planet.append doesn't work either
TypeError: 'str' object does not support item assignment
3) Méthodes de chaînes (exemples)
claim = "Pluto is a planet!"
print(claim.upper())
print(claim.lower())
print(claim.capitalize())
print(claim.title())
print(claim.count("a")) # 2
print(claim.count("Pluto")) # 1
print(claim.count("pluto")) # 0
print(claim.index("plan")) # 11
print(claim.startswith("Pluto"))
print(claim.endswith("planet")) # False (il manque '!')
Sortie
PLUTO IS A PLANET! pluto is a planet! Pluto is a planet! Pluto Is A Planet! 2 1 0 11 True False
4) chaînes et listes : split / join
claim = "Pluto is a planet!"
words = claim.split() # split par défaut = espaces
print(words)
datestr = "1956-01-31"
year, month, day = datestr.split("-")
print("/".join([month, day, year]))
print(" 👏 ".join([w.upper() for w in words]))
Sortie
['Pluto', 'is', 'a', 'planet!'] 01/31/1956 PLUTO 👏 IS 👏 A 👏 PLANET!
5) Construire des chaînes : concaténation et str.format()
planet = "Pluto"
print(planet + ", we miss you.")
position = 9
print(planet + ", you'll always be the " + str(position) + "th planet to me.")
print(planet + ", you'll always be the " + position + "th planet to me.") # ❌ TypeError
Sortie
Pluto, we miss you. Pluto, you'll always be the 9th planet to me.
TypeError Traceback (most recent call last) /tmp/ipykernel_19/xxxx.py in <module> 1 position = 9 ----> 2 planet + ", you'll always be the " + position + "th planet to me."
TypeError: can only concatenate str (not "int") to str
Avec str.format(), plus lisible (et conversion auto des types) :
planet = "Pluto"
position = 9
print("{}, you'll always be the {}th planet to me.".format(planet, position))
pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
print("{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians."
.format(planet, pluto_mass, pluto_mass / earth_mass, population))
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format("planet", "dwarf planet")
print(s)
Sortie
Pluto, you'll always be the 9th planet to me. Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians. Pluto's a planet. No, it's a dwarf planet. planet! dwarf planet!
6) Dictionnaires : bases
Un dictionnaire mappe des clés vers des valeurs.
numbers = {"one": 1, "two": 2, "three": 3}
print(numbers["one"])
numbers["eleven"] = 11 # ajout
print(numbers)
numbers["one"] = "Pluto" # modification
print(numbers)
Sortie
1
{'one': 1, 'two': 2, 'three': 3, 'eleven': 11}
{'one': 'Pluto', 'two': 2, 'three': 3, 'eleven': 11}
7) Compréhensions de dictionnaires et appartenance
planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
planet_to_initial = {planet: planet[0] for planet in planets}
print(planet_to_initial)
print("Saturn" in planet_to_initial)
print("Betelgeuse" in planet_to_initial)
Sortie
{'Mercury': 'M', 'Venus': 'V', 'Earth': 'E', 'Mars': 'M', 'Jupiter': 'J', 'Saturn': 'S', 'Uranus': 'U', 'Neptune': 'N'}
True
False
8) Itérer sur un dictionnaire
Boucler sur les clés :
numbers = {"one": "Pluto", "two": 2, "three": 3, "eleven": 11}
for k in numbers:
print("{} = {}".format(k, numbers[k]))
Sortie
one = Pluto two = 2 three = 3 eleven = 11
Récupérer toutes les clés ou toutes les valeurs :
# Initiales triées, jointes par un espace
print(" ".join(sorted(planet_to_initial.values())))
Sortie
E J M M N S U V
Itérer sur (clé, valeur) avec .items() :
for planet, initial in planet_to_initial.items():
print("{} begins with \"{}\"".format(planet.rjust(10), initial))
Sortie
Mercury begins with "M" Venus begins with "V" Earth begins with "E" Mars begins with "M" Jupiter begins with "J" Saturn begins with "S" Uranus begins with "U" Neptune begins with "N"
9) Aide intégrée
help(dict)
Sortie (extrait)
Help on class dict in module builtins:
class dict(object) | dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs | dict(iterable) -> new dictionary initialized as if via: | d = | for k, v in iterable: | d[k] = v | dict(**kwargs) -> new dictionary initialized with the name=value pairs | in the keyword argument list. |
| Methods defined here: |
| contains(self, key, /) | True if the dictionary has the specified key, else False. | ...
🚀 Conclusion
Vous savez maintenant :
- manipuler des chaînes (syntaxe, échappement, méthodes, formatage),
- convertir entre chaînes et listes avec
split/join, - créer et modifier des dictionnaires, tester l’appartenance, itérer sur les clés/valeurs,
- et écrire des compréhensions de dictionnaires.