← Retour à 2.2 Python - Strings

Voici une solution pour chaque exercice du notebook du challenge. Ce n’est pas la seule possible : si ton code produit le même résultat, il est tout aussi valable !

Mission 1

What’s the length of the following string?

s = "Taumata whakatangihanga koauau o tamatea turi pukaka piki maungah oronuku pokai whenuaki tanatahu "

print(len(s))   # 98

La fonction len() renvoie le nombre de caractères d’une chaîne, espaces compris (y compris l’espace final).

Now, count only non-space characters and display how many there are.
Remember, using a for loop on a string will browse all the individual characters of it!

s = "Taumata whakatangihanga koauau o tamatea turi pukaka piki maungah oronuku pokai whenuaki tanatahu "

compteur = 0
for caractere in s:
    if caractere != " ":
        compteur += 1

print(compteur)   # 85

La chaîne contient 13 espaces : 98 - 13 = 85.

Mission 2

Ask the user for a string, then for a character (we assume user input follows the rules). Then, display the positions, starting with 1, of all occurrences of the character within the string.

For example, for the word “welcome” and for the character “e”, the script will display:

position: 2  
position: 7
chaine = input("Enter a string: ")
caractere = input("Enter a character: ")

for i in range(len(chaine)):
    if chaine[i] == caractere:
        print("position:", i + 1)

Les positions Python commencent à 0 : on ajoute 1 à l’index i pour afficher une position qui commence à 1. Si le caractère n’apparaît pas dans la chaîne, rien ne s’affiche.

Mission 3

Ask the user for a string, then for an integer. Then, display the string repeated as many times as the given integer.

For example, badger and 4 will display badgerbadgerbadgerbadger.

chaine = input("Enter a string: ")
nombre = int(input("Enter an integer: "))

resultat = ""
for i in range(nombre):
    resultat += chaine

print(resultat)

On part d’une chaîne vide, à laquelle on concatène la chaîne saisie autant de fois que demandé. Avec 0, la boucle ne s’exécute pas et on affiche une chaîne vide.

Remarque : en Python, on peut aussi multiplier une chaîne par un entier : print(chaine * nombre) donne le même résultat.

Mission 4

Display the following string without including the spaces at the beginning and end. There’s a string method that does exactly that, look at the documentation!

s = "   Data Analyst  "

print(s.strip())   # Data Analyst

La méthode .strip() renvoie une copie de la chaîne sans les espaces du début et de la fin. L’espace entre « Data » et « Analyst » est conservée.

Mission 5

Ask the user for a string, then for a character, then for another character.

Then, display the string where the occurrences of the first character are replaced by the second one.

chaine = input("Enter a string: ")
ancien = input("Enter the character to replace: ")
nouveau = input("Enter the new character: ")

print(chaine.replace(ancien, nouveau))

Comme vu dans la ressource, .replace() ne modifie pas chaine (les chaînes sont immuables) : elle renvoie une nouvelle chaîne, qu’on affiche directement.

Mission 6

Ask the user for a string. Then, display the same string with all vowels (a, e, i, o, u) converted to uppercase, and all consonants converted to lowercase.

For example, "Papa's got a brand new bag" gives "pApA's gOt A brAnd nEw bAg".

chaine = input("Enter a string: ")

resultat = ""
for caractere in chaine:
    if caractere.lower() in "aeiou":
        resultat += caractere.upper()
    else:
        resultat += caractere.lower()

print(resultat)

Comme une chaîne est immuable, on construit le résultat caractère par caractère dans une nouvelle chaîne. caractere.lower() in "aeiou" vérifie si le caractère (mis en minuscule) fait partie des voyelles. Les espaces et la ponctuation ne sont pas modifiés par .lower().