Программа Python для подсчета количества пробелов в строке
В этой статье мы рассмотрим программу Python для подсчета количества пробелов в строке.
Используемые методы
Ниже приведены различные методы выполнения этой задачи:
Использование цикла for (с индексацией)
Использование функции count()
Использование функции isspace()
-
Использование функции Счетчик()
Использование функции countOf() операторского модуля
Предположим, мы взяли входную строку. теперь мы посчитаем количество пробелов во входной строке вышеприведенных методов.
Способ 1: использование цикла for (с индексацией)
Алгоритм (шаги)
Ниже приводится алгоритм/шаги, которые необходимо выполнить для выполнения желаемой задачи.
Создайте функцию countSpaces(), чтобы возвращать количество пробелов в строке, принимая входную строку в качестве аргумента.
Инициализируйте переменную значением 0, чтобы сохранить общее количество пробелов.
Используйте цикл for для перемещения до длины строки с помощью функции len() (возвращает количество элементов в объекте).
Используйте условный оператор if, чтобы проверить, является ли каждый символ строки пробелом/пробелом или нет.
Увеличение значения счетчика на 1, если вышеуказанное условие верно.
Возвращает количество пробелов во входной строке.
-
Создайте переменную для хранения входной строки.
Вызовите определенную выше функцию countSpaces(), передав входную строку в качестве аргумента.
Пример
Следующая программа возвращает количество пробелов во входной строке, используя цикл for (с индексацией) –
# function to return the count of no of spaces in a string
# by accepting the input string as an argument
def countSpaces(inputString):
# storing the count of the number of spaces in a given string
spaces_count = 0
# Traversing till the length of the string
for index in range(0, len(inputString)):
# checking whether each character of a string is blank/space or not
if inputString[index] == " ":
# incrementing the space value count by 1
spaces_count += 1
# returning the count of the number of spaces in an input string
return spaces_count
# input string
inputString = "tutorialspoint is a best learning platform for coding"
# calling the above defined countSpaces() function by
# passing input string as an argument
print("Count of no of spaces in an input string:", countSpaces(inputString))
Выход
При выполнении вышеуказанная программа сгенерирует следующий вывод:
Count of no of spaces in an input string: 7
Способ 2: использование функции count()
функция count() — возвращает номер. сколько раз данное значение встречается в строке.
Синтаксис
string.count(value, start, end)
Пример
Следующая программа возвращает количество пробелов во входной строке с помощью функции count():
# creating a function to return the count of no of spaces in a string
# by accepting the input string as an argument
def countSpaces(inputString):
# returing the spaces count in a string using the count() function
return inputString.count(" ")
# input string
inputString = "hello tutorialspoint python"
# calling the above defined countSpaces() function by
# passing input string as an argument
print("Count of no of spaces in an input string:",countSpaces(inputString))
Выход
При выполнении вышеуказанная программа сгенерирует следующий вывод:
Count of no of spaces in an input string: 2
Способ 3: использование функции isspace()
функция isspace() – возвращает True, если все символы, присутствующие в строке, являются пробелами, в противном случае — False.
Синтаксис
string.isspace()
Пример
Следующая программа возвращает количество пробелов во входной строке с помощью функции isspace():
# input string
inputString = "hello tutorialspoint python codes"
# storing the count of spaces
spaces_count = 0
# traversing through each character of the input string
for c in inputString:
# checking whether the current character is space or not using isspace() function
if(c.isspace()):
# incrementing the spaces_count value by 1 if the condition is true
spaces_count += 1
# printing the count of no of spaces in an input string
print("Count of no of spaces in an input string:", spaces_count)
Выход
При выполнении вышеуказанная программа сгенерирует следующий вывод:
Count of no of spaces in an input string: 3
Способ 4: использование функции Counter()
Функция Counter() — подкласс, который подсчитывает хэшируемые объекты. Он неявно создает хеш-таблицу итерируемого объекта при вызове/вызове.
Здесь функция Counter() возвращает частоту каждого символа входной строки в виде пары ключ-значение.
Пример
Следующая программа возвращает количество пробелов во входной строке с помощью функции Counter():
# importing a Counter function from the collections module
from collections import Counter
# input string
inputString = "hello tutorialspoint python codes"
# getting the frequency of each character of the string as a
# key-value pair using Counter() function
frequency = Counter(inputString)
# getting the frequency/count of spaces
spaces_count = frequency[' ']
# printing the count of no of spaces in an input string
print("Count of no of spaces in an input string:", spaces_count)
Выход
При выполнении вышеуказанная программа сгенерирует следующий вывод:
Count of no of spaces in an input string: 3
Способ 5. Использование функции countOf() модуля оператора.
Пример
Следующая программа возвращает количество пробелов во входной строке, используя функцию countOf() модуля оператора:
# importing operator module with alias name op
import operator as op
# creating a function to return the count of no of spaces in a string
# by accepting the input string as an argument
def countSpaces(inputString):
# returing the spaces count in a string using the countOf() function
return op.countOf(inputString, " ")
# input string
inputString = "hello tutorialspoint python"
# calling the above defined countSpaces() function by
# passing input string as an argument
print("Count of no of spaces in an input string:", countSpaces(inputString))
Выход
При выполнении вышеуказанная программа сгенерирует следующий вывод:
Count of no of spaces in an input string: 2
Заключение
В этой статье мы рассмотрели 5 различных методов подсчета количества пробелов в строке. Используя новую операторную функцию countOf, мы научились подсчитывать элемент в любой итерации. Мы также научились подсчитывать частоты каждого элемента итерации с помощью словарного хеширования.