Count numbers in string python

Python String count() with EXAMPLES

The count() is a built-in function in Python. It will return the total count of a given element in a string. The counting begins from the start of the string till the end. It is also possible to specify the start and end index from where you want the search to begin.

The syntax for PythonString Count()

Python count function syntax:

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

Parameters of Python Syntax

  • Char or substring: You can specify a single character or substring you are wants to search in the given string. It will return you the count of the character or substring in the given string.
  • start : (optional) It indicates the start index from where the search will begin. If not given, it will start from 0. For example, you want to search for a character from the middle of the string. You can give the start value to your count function.
  • end: (optional) It indicates the end index where the search ends. If not given, it will search till the end of the list or string given. For example, you don’t want to scan the entire string and limit the search till a specific point you can give the value to end in your count function, and the count will take care of searching till that point.
Читайте также:  Reading mat files in python

ReturnValue

The count() method will return an integer value, i.e., the count of the given element from the given string. It returns a 0 if the value is not found in the given string.

Example 1: Count Method on a String

The following example shows the working of count() function on a string.

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)
The count of 'o' is 2 The count of 'o' usingstart/end is 1

Example 2: Count occurrence of a character in a given string

The following example shows the occurrence of a character in a given string as well as in by using the start/end index.

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)
The count of 'u' is 3 The count of 'u' usingstart/end is 2

Example 3: Count occurrence of substring in a given string

Following example shows the occurrence of substring in a givenstring as well as usingstart/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)
The count of 'to' is 2 The count of 'to' usingstart/end is 1

Summary

  • The count() is a built-in function in Python. It will return you the count of a given element in a list or a string.
  • In the case of a string, the counting begins from the start of the string till the end. It is also possible to specify the start and end index from where you want the search to begin.
  • The count() method returns an integer value.
Читайте также:  Valueerror math domain error питон

Источник

Как подсчитать количество чисел в строке в Python: 4 простых способа

Как подсчитать количество чисел в строке в Python: 4 простых способа

В этой статье мы рассмотрим, как определить количество чисел в строке, используя различные методы, а также приведем примеры кода для каждого из них.

1. Метод split() и функция str.isdigit()

Один из способов определить количество чисел в строке – использовать метод split() для разделения строки на список слов, а затем применить функцию str.isdigit() для проверки, является ли слово числом.

def count_numbers_in_string(s): words = s.split() count = 0 for word in words: if word.isdigit(): count += 1 return count s = "123 яблоко 45 груша 6789 банан 10" print(count_numbers_in_string(s)) #4

2. Регулярные выражения

Регулярные выражения являются мощным инструментом для поиска и работы со строками. В данном случае мы можем использовать модуль re для поиска всех чисел в строке.

import re def count_numbers_in_string(s): numbers = re.findall(r'\d+', s) return len(numbers) s = "123 яблоко 45 груша 6789 банан 10" print(count_numbers_in_string(s)) #4

3. Использование метода str.split() с регулярными выражениями

Мы можем также использовать комбинацию метода split() и регулярных выражений для разделения строки на список чисел и подсчета их количества.

import re def count_numbers_in_string(s): words = re.split(r'\D+', s) count = 0 for word in words: if word: count += 1 return count s = "123 яблоко 45 груша 6789 банан 10" print(count_numbers_in_string(s)) #4

4. Использование списковых включений (list comprehensions)

Списковые включения – это элегантный способ создания списков на основе существующих коллекций. В данном случае мы можем использовать списковые включения для создания списка чисел и подсчета их количества.

def count_numbers_in_string(s): words = s.split() numbers = [word for word in words if word.isdigit()] return len(numbers) s = "123 яблоко 45 груша 6789 банан 10" print(count_numbers_in_string(s)) #4

Заключение

Каждый из представленных методов имеет свои преимущества и недостатки. Метод split() и функция str.isdigit() являются простыми и понятными, но могут быть менее гибкими при работе с разными форматами чисел. Регулярные выражения предлагают больше возможностей для поиска и обработки чисел, однако могут быть сложными для понимания и избыточными для простых задач. Списковые включения являются компактными и эффективными, но могут быть менее читаемыми для новичков.

Выбирая подходящий метод, стоит учитывать характеристики исходных данных, а также личные предпочтения и опыт работы с Python. В любом случае, знание различных методов работы со строками и числами позволяет более гибко и эффективно решать задачи на Python.

Функции all() и any() в Python: для чего нужны и примеры использования

Функции all() и any() в Python: для чего нужны и примеры использования

Метод remove() в Python: синтаксис, описание и примеры работы с различными последовательностями

Метод remove() в Python: синтаксис, описание и примеры работы с различными последовательностями

Анонимные (lambda) функции в Python: синтаксис, описание и примеры работы

Анонимные (lambda) функции в Python: синтаксис, описание и примеры работы

Использование срезов для манипулирования списками в Python

Использование срезов для манипулирования списками в Python

Как использовать логические операторы and, or и not в Python — разбираем на примерах

Как использовать логические операторы and, or и not в Python — разбираем на примерах

Главное о переменных в Python: объявление, присваивание, удаление, именование

Главное о переменных в Python: объявление, присваивание, удаление, именование

Источник

Count numbers in string in Python [5 Methods]

In this Python tutorial, we will understand how to count numbers in string in Python using examples.

In Python, we can count numbers from a string using the following 5 methods:

  • Using isalpha() method
  • Using all digits list
  • Using isnumeric() method
  • Using re module
  • Using ord() function

Let us start with the isnumeric() method.

Count numbers in string in Python using isnumeric()

In this section, we will learn how to count numbers in string in Python using the isnumeric() method.

The Python isnumeric() is a string method that return TRUE only when the character defined in string is numeric. However, if the character is not numeric, it will return FALSE.

Let us understand how to use this method to fetch the count of numbers in string in Python.

# Defing a string with numbers string = "Arizona29876" # Initializing count count = 0 # Iterating over all characters for num in string: # Check character is digit (number) if num.isnumeric(): # Increment the value of count count += 1 # Final count print("Total numbers found:-", count)
  • In the example, we utilized the for loop to iterate over each character defined in the string.
  • After this, we used the isnumeric() method to check if the character is numeric or not. And based on this, we are calculating the count.

Here is the final result of the above Python program.

Count numbers in string in Python

So, here we seen how to count numbers in string in Python using isnumeric() method.

Count numbers in string in Python using isalpha()

This section will illustrate how to use the isalpha() method to check the count of numbers from Python string.

The Python isalpha() method allows us to check if a character in a given string is alphabet or not (a-z). So, this method returns TRUE, if the character is alphabet, else it returns FALSE.

Let us understand its use in Pyhton with the help of an example.

# Defing a string with numbers string = "Chicago09876545" # Initializing count alpha_count = 0 # Iterating over all characters for char in string: # Check character is alphabet if char.isalpha(): # Increment the value of count alpha_count += 1 # num_count num_count = len(string)-alpha_count # Final count print("Total numbers found:-", num_count)
  • In the above Python code, we used the isalpha() method to first count the number of characters that are the alphabet in the given string.
  • Next, we calculated the count of numbers by subtracting the alphabet character count from the total length of the string.

Here is the end of the Python program where the string is Chicago09876545.

Count numbers in Python String

So, here we seen how to count the numbers in string in Python using isalpha() method.

Count numbers in string in Python using all digit list

In this section, we will understand how to count numbers in Python string using a list.

So, in this approach, we will first create a list containing all digits in string format. And then, we will check the existence of digit from string using the list.

Here is the example explaining this approach in Python program

# Defing a string with numbers string = "Seattle987654" # Defining list of digits numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] # Initializing count count = 0 # Iterating over all characters for num in string: # Check character is digit (number) using list if num in numbers: # Increment the value of count count += 1 # Final count print("Total numbers found:-", count)
  • In this example, we are using the numbers list to check the existence of a digit in the given string.
  • And based on the existence, we are calculating the count and printing the result.

Count numbers in Python String Example

So, here we seen how to count the numbers in string in Python using Python List.

Count numbers in string in Python using re module

In this section, we will understand the use of re module in Python to calculate the count of numbers from a Python String.

In findall() method in re module examines the given string from left to right and then, it return all the matching patterns. And in this example, we will define a pattern to search only for numbers (digits) from the string.

The example related to this implementation is given below.

# Importing re module import re # Defing a string with numbers string = "Washington76805" # Counting digits using finall() and len() count = len(re.findall('2', string)) # Final count print("Total numbers found:-", count)
  • In the example, we utilized the findall() method to first extract all the numbers given in the string.
  • After this, we used the len() function to get the count of the matching numbers.

So, when we run the above Python program, we will get the count of numbers from the given string.

Count numbers in Python String using re

So, here we seen how to count the numbers in string in Python using re.finall() method.

Count numbers in string in Python using ord()

This section will illustrate how to use the ord() function in Python to get the count of numbers from a given string.

The basic use of the ord() function in Python is to get the Unicode for any given character. And in this method, we will use ord() function to get the unicode for the digits starting from 0 to 1.

Then we will use the IF statement to check if the unicode for each character in the string matches any of the unicode for digits. And based upon this logic, we will calculate the count of numbers (digits).

The example related to this execution in Python is given below.

# Defing a string with numbers string = "324Boston123" # Initializing count count = 0 # Iterating over all characters for num in string: # Check character is digit (number) if ord(num) in range(48,58): # Increment the value of count count += 1 # Final count  print("Total numbers found:-", count)

Once we execute the above Python program, we will get the following result.

Count numbers in Python String using ord

So, here we seen how to count the numbers in string in Python using ord() function.

Conclusion

In this Python tutorial, we understood to get the count of numbers in string in Python using 5 different methods. Moreover, to explain each method, we illustrated multiple examples.

You may also like to read the following Python tutorials.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Оцените статью