Working with strings · Travailler avec des chaînes
Letters have positions
- A string is a row of characters.
- Each character has a position, called an index.
- Indexes start at
0. Uses[-1]for the last character.
Les lettres ont des positions
- Une chaîne est une rangée de caractères.
- Chaque caractère a une position, appelée un index.
- Les indices commencent à
0. Utilisezs[-1]pour le dernier caractère.
word = "Python"
print(word[0])
print(word[-1])
Take a slice
- A slice takes part of a string:
s[start:end]. - The character at
endis not included. - Leave a side empty for "from the start" or "to the end":
s[:3],s[2:].
Prendre une tranche
- Une tranche prend une partie d'une chaîne :
s[start:end]. - Le caractère à
endn'est pas inclus. - Laissez un côté vide pour "du début" ou "jusqu'à la fin" :
s[:3],s[2:].
msg = "hello"
print(msg[:3])
print(msg[2:])
Worked example: positions and slices
- In
"banana"the positions areb=0,a=1,n=2,a=3,n=4,a=5. word[0]is the first letter;word[-1]counts back from the end.word[:3]takes positions 0, 1 and 2, and stops before 3.
Exemple résolu : positions et tranches
- Dans
"banana", les positions sontb=0,a=1,n=2,a=3,n=4,a=5. word[0]est la première lettre ;word[-1]compte à rebours depuis la fin.word[:3]prend les positions 0, 1 et 2, et s'arrête avant 3.
word = "banana"
print(word[0]) # b
print(word[-1]) # a (the last letter)
print(word[:3]) # ban (positions 0, 1, 2)
print(word[2:5]) # nan (positions 2, 3, 4)
Length and changing case
len(s)gives the number of characters.s.upper()makes a CAPITAL copy;s.lower()makes a lowercase copy.- These make a new string; the original does not change.
Longueur et modification de la casse
len(s)donne le nombre de caractères.s.upper()crée une copie en MAJUSCULES ;s.lower()crée une copie en minuscules.- Cela crée une nouvelle chaîne ; l'originale ne change pas.
city = "Tokyo"
print(len(city))
print(city.upper())
print(city.lower())
f-strings build text
- An f-string starts with
fbefore the quote. - Put a value inside
{ }and Python drops it into the text. - It is the neat way to mix words and values.
Les f-strings construisent du texte
- Une f-string commence par
favant la guillemet. - Mettez une valeur à l'intérieur de
{ }et Python l'y insère. - C'est la façon propre de mélanger des mots et des valeurs.
fruit = "apple"
count = 3
print(f"I have {count} {fruit}s")
Common mistakes
- Indexing starts at
0;s[-1]is the last character. - Strings cannot be changed in place — methods like
.upper()return a NEW string, so store the result. - You can only join a string to a string with
+.
Erreurs courantes
- L'indexation commence à
0;s[-1]est le dernier caractère. - Les chaînes ne peuvent pas être modifiées sur place — les méthodes comme
.upper()retournent une NOUVELLE chaîne, donc stockez le résultat. - Vous ne pouvez joindre qu'une chaîne à une chaîne avec
+.
Now you try
- Read the task to see which variable to fill or what to print.
- Press Check answer to test your code.
À vous maintenant
- Lisez la tâche pour voir quelle variable remplir ou quoi imprimer.
- Appuyez sur Vérifier la réponse pour tester votre code.
Index & slice a string · Index et tranchage d'une chaîne
Each character has an index from 0; a slice · tranche s[a:b] takes a range. · Chaque caractère a un index allant de 0 ; un tranche s[a:b] prend une plage.
word is "computer". Store its first · premier character in first. Indexes start at 0, so that character is word[0]. · word est "computer". Stockez son premier caractère dans first. Les index commencent à 0, donc ce caractère est word[0].
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
first is already the first character of "computer". Store the first four characters in first_four with a slice. word[a:b] stops before b, so four characters is word[:4]. · first est déjà le premier caractère de "computer". Stockez les quatre premiers caractères dans first_four avec un tranche. word[a:b] s'arrête avant b, donc quatre caractères correspondent à word[:4].
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
phrase is "Hello World". Store its length in n with len(...), and an UPPERCASE copy in loud with .upper(). · phrase est "Hello World". Stockez sa longueur dans n avec len(...), et une copie en MAJUSCULES dans loud avec .upper().
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
name is "Mia" and · et age is 12. Use an f-string to print exactly: Mia is 12 years old. · name est "Mia" et age est 12. Utilisez une chaîne f pour afficher exactement : Mia is 12 years old.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
first is "ada" and · et last is "lovelace". Store the initials in initials as capital letters, each followed by a dot: "A.L.". · first est "ada" et last est "lovelace". Stockez les initiales dans initials comme des lettres majuscules, chacune suivie d'un point : "A.L.".
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.