Fabrication industrielle
Internet des objets industriel | Matériaux industriels | Entretien et réparation d'équipement | Programmation industrielle |
home  MfgRobots >> Fabrication industrielle >  >> Industrial programming >> Python

Python String count() avec des EXEMPLES

Compte Python

Le count() est une fonction intégrée à Python. Il renverra le nombre total d'un élément donné dans une chaîne. Le comptage commence du début de la chaîne jusqu'à la fin. Il est également possible de spécifier l'index de début et de fin à partir duquel vous souhaitez que la recherche commence.

Dans ce tutoriel Python, vous apprendrez :

La syntaxe de PythonString Count()

Syntaxe de la fonction de comptage Python :

string.count(char or substring, start, end)

Paramètres de la syntaxe Python

Valeur de retour

La méthode count () renverra une valeur entière, c'est-à-dire le nombre de l'élément donné à partir de la chaîne donnée. Il renvoie un 0 si la valeur n'est pas trouvée dans la chaîne donnée.

Exemple 1 :Méthode Count sur une chaîne

L'exemple suivant montre le fonctionnement de la fonction count() sur une chaîne.

str1 = "Hello World"
str_count1 = str1.count('o')  # counting the character “o” in the givenstring
print("The count of 'o' is", str_count1)

str_count2 = str1.count('o', 0,5)
print("The count of 'o' usingstart/end is", str_count2)

Sortie :

The count of 'o' is 2
The count of 'o' usingstart/end is 1

Exemple 2 :Compter l'occurrence d'un caractère dans une chaîne donnée

L'exemple suivant montre l'occurrence d'un caractère dans une chaîne donnée ainsi qu'en utilisant l'index de début/fin.

str1 = "Welcome to Guru99 Tutorials!"
str_count1 = str1.count('u')  # counting the character “u” in the given string
print("The count of 'u' is", str_count1)

str_count2 = str1.count('u', 6,15)
print("The count of 'u' usingstart/end is", str_count2)

Sortie :

The count of 'u' is 3
The count of 'u' usingstart/end is 2

Exemple 3 :Compter l'occurrence d'une sous-chaîne dans une chaîne donnée

L'exemple suivant montre l'occurrence de la sous-chaîne dans une chaîne donnée ainsi que l'utilisation de start/endindex.

str1 = "Welcome to Guru99 - Free Training Tutorials and Videos for IT Courses"
str_count1 = str1.count('to') # counting the substring “to” in the givenstring
print("The count of 'to' is", str_count1)
str_count2 = str1.count('to', 6,15)
print("The count of 'to' usingstart/end is", str_count2)

Sortie :

The count of 'to' is 2
The count of 'to' usingstart/end is 1

Résumé :


Python

  1. Python String strip() Fonction avec EXAMPLE
  2. Python String format() Expliquer avec des EXEMPLES
  3. Méthode Python String find() avec exemples
  4. Fonctions Python Lambda avec EXEMPLES
  5. Fonction Python round() avec EXEMPLES
  6. Fonction Python map() avec EXEMPLES
  7. Python Timeit() avec des exemples
  8. Compteur Python dans les collections avec exemple
  9. type() et isinstance() en Python avec des exemples