Exercise 17
Write a Python program to display for a given string of characters "s", the number of occurrences of each character in the string "s".
Example for the string s = "Python.org" the program should display:
The character: "P" appears once in the string s
The character: "y" appears once in the string s
The character: "t" appears once in the string s
The character: "h" appears once in the string s
The character: "o" appears twice in the string s
The character: "n" appears once in the string s
The character: ". " appears once in the string s
The character: "r" appears once in the string s
The character: "g" appears once in the string s
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
s = "Python is a programming language" # group the characters of s into a set to avoid repetition unique =set({}) for x in s: if x not in unique: unique.add(x) print("The number of occurrences of the character: ", x, " in the string s is:", s.count(x)) """ Which displays after execution: The number of occurrences of the character: P in the string s is: 1 The number of occurrences of the character: y in the string s is: 1 The number of occurrences of the character: t in the string s is: 1 The number of occurrences of the character: h in the string s is: 1 The number of occurrences of the character: o in the string s is: 2 The number of occurrences of the character: n in the string s is: 3 The number of occurrences of the character: in the string s is: 4 The number of occurrences of the character: i in the string s is: 2 The number of occurrences of the character: s in the string s is: 1 The number of occurrences of the character: a in the string s is: 4 The number of occurrences of the character: p in the string s is: 1 The number of occurrences of the character: r in the string s is: 2 The number of occurrences of the character: g in the string s is: 4 The number of occurrences of the character: m in the string s is: 2 The number of occurrences of the character: l in the string s is: 1 The number of occurrences of the character: u in the string s is: 1 The number of occurrences of the character: e in the string s is: 1 """ |
Younes Derfoufi
CRMEF OUJDA
Acheter sur Très Facile !
-
Wireless Souris Gamer Rechargeable 3200 - G-Lab-Xbox-Ps5-PC
€ 17,00 Acheter le produit -
Programmation Python pour les sciences de la vie
€ 26,00 Acheter le livre -
AILKIN 2024 est un amplificateur WiFi ultra-performant, avec 1200 Mbps, double bande 5 GHz et 2,4 GHz, et 4 antennes puissantes, compatible avec tous les réseaux.
€ 31,00 Acheter le produit
1 thought on “Solution Exercise 17: number of occurrences of a character in a Python string”