Python 3 make the program discover how much of a given digit has a string or a number

2

It's for python 3:

I'm trying to do a pretty basic program to figure out how much of a given digit it has in a string or a number.

For example, if the user types 1200, I want to print- "your number has 2 zeros" .... or if the user types "hi, alright?" I want to print- "your phrase has 2 'o's

    
asked by anonymous 25.08.2017 / 07:55

2 answers

2
  

See working at repl
  Code in github

# coding: utf-8

# Informe uma frase
frase = input("Informe uma frase: ")
# Informe qual o caractere que deseja saber a quantidade contida na frase
caracter = input("Informe o caracter que deseja contar: ")
# método: count - Conta quantas vezes o caractere foi usado na frase
# Imprime a quantidade.
print("Sua frase tem: " + str(frase.count(caracter)) + " digito(s): " + str(caracter))
  

Source: original question English

    
25.08.2017 / 08:20
3

Extending the answer from @ Wéllingthon M. de Souza who answered your question well, here are two alternatives in case you want to count all the characters:

from collections import Counter

frase = input("Informe uma frase: ")
count_chars = Counter(frase)

text = '\n'.join('A Frase tem {} {}'.format(v, k) for k, v in count_chars.items())
print(text)

STATEMENT

In a slightly more didactic way it can be:

frase = input("Informe uma frase: ")

count_chars = {}
for char in frase:
    if char not in count_chars:
        count_chars[char] = 0
    count_chars[char] += 1

for char in count_chars:
    print('A Frase tem {} {}'.format(count_chars[char], char))

DEMONSTRATION

    
25.08.2017 / 11:07