3
def charcount(stri):
    for i in stri:
        count = 0
        for j in stri:
            if stri[i] == stri[j]:
                count += 1

I am new to python and currently learning string operations, can anyone tell me what is wrong in this program? The function tries to print a count of each character in given string.

For eg: string ="There is shadow behind you" I want to count how many times each character have come in string

4
  • 1
    Please be careful to properly format python code in a question. Unformatted python is meaningless. I formatted it for you (leaving it exactly how you had it). That said: Can you explain what you're observing? And what you expect (e.g. sample input and output)? Right now it's just "here's my code - debug it for me." Please edit your question to be more specific. Commented Jan 29, 2018 at 5:41
  • May I know what are you trying to achieve in your code, as you are checking if stri[i] == stri[j]? you can edit your question properly along with a example and expected output Commented Jan 29, 2018 at 5:46
  • i and j are not indices but characters out of stri. That is how for loops work in python. Therefore you want to directly compare i to j. Also , if you want something printed, typically you'll have to make a print statement. Commented Jan 29, 2018 at 5:48
  • What is your expected output? Just a bunch of counts, or pairs of character and count? Commented Jan 29, 2018 at 5:49

9 Answers 9

7

Counting characters in a string can be done with the Counter() class like:

Code:

from collections import Counter

def charcount(stri):
    return Counter(stri)

print(charcount('The function try to print count of each character '
                'in given string . Please help'))

Results:

Counter({' ': 14, 'e': 7, 'n': 7, 't': 7, 'c': 5, 'i': 5, 
         'r': 5, 'h': 4, 'o': 4, 'a': 4, 'f': 2, 'u': 2, 
         'p': 2, 'g': 2, 's': 2, 'l': 2, 'T': 1, 'y': 1, 
         'v': 1, '.': 1, 'P': 1})
Sign up to request clarification or add additional context in comments.

1 Comment

in_l = ','.join(str(input('Put a string: '))).split(',') d1={} for i in set(in_l): d1[i] = in_l.count(i) print(d1)
1

Feedback on code:

In these lines:

for i in stri:
    count = 0
    for j in stri:

The outer loop is looping over each character in stri, and the inner loop is looping over every character in stri. This is like a Cartesian product of the elements in the list, and is not necessary here.

Secondly, in this line:

if stri[i] == stri[j]:

You are accessing stri by its indices, but i and j are not indices, they are the characters themselves. So treating them as indices does not work here, since characters are not valid indices for lists. If you wanted to access just the indices, you could access them with range(len()):

for i in range(len(stri)):
    count = 0
    for j in range(len(stri)):
        if stri[i] == stri[j]:

Or if you want to access the elements and their indices, you can use enumerate().

Having said this, your approach is too complicated and needs to be redone. You need to group your characters and count them. Using nested loops is overkill here.

Alternative approaches:

There are lots of better ways to do this such as using collections.Counter() and dictionaries. These data structures are very good for counting.

Since it also looks like your struggling with loops, I suggest going back to the basics, and then attempt doing this problem with a dictionary.

Comments

1

Counting each characters in a string

>>> from collections import Counter
>>> string ="There is shadow behind you"
>>> Counter(string)
Counter({' ': 4, 'h': 3, 'e': 3, 'i': 2, 's': 2, 'd': 2, 'o': 2, 'T': 1, 'r': 
1, 'a': 1, 'w': 1, 'b': 1, 'n': 1, 'y': 1, 'u': 1})

Comments

0

This is what you need to do. Iterate through the input string and use a hash to keep track of the counts. In python, the basic hash is a dictionary.

def charCounter(string):
    d = {} # initialize a new dictionary
    for s in string:
        if s not in d:
            d[s] = 1
        else:
            d[s] += 1
    return d

print charCounter("apple") 
# returns {'a': 1, 'p': 2, 'e': 1, 'l': 1}

Comments

0

Just little modification in your solution

first you are looping wrong:-

Take a look:-

def charcount(stri):
    d = {}
    for i in stri:

        if i in d:
            d[i] = d[i] +1
        else:
          d[i] = 1
    return d

print (charcount("hello")) #expected outpu

Comments

0

If you don't want to use any import :

def charcount(string):
        occurenceDict = dict()
        for char in string:
            if char not in occurenceDict:
                occurenceDict[char] = 1
            else :
                occurenceDict[char] += 1
        return(occurenceDict)

Comments

0
You can use the following code.
in_l = ','.join(str(input('Put a string: '))).split(',')
d1={}
for i in set(in_l):
    d1[i] = in_l.count(i)
print(d1)

Comments

0

public class Z {

public static void main(String[] args) {

    int count=0;

    String str="aabaaaababa";

    for(int i=0;i<str.length();i++) {

        if(str.charAt(i)=='a') {

            count++;
            
        }

    }

    System.out.println(count);

}

}

1 Comment

This is not Python. The question is specifically about Python.
0

You can also just split by the char and take the length -1:

def charCounter(string,char):
    return len(string.split(char))-1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.