user3340270
user3340270

Reputation: 187

How to count the number of letters in a string with a list of sample?

value = 'bcdjbcdscv'
value = 'bcdvfdvdfvvdfvv'
value = 'bcvfdvdfvcdjbcdscv'

def count_letters(word, char):
    count = 0
    for c in word:
     if char == c:
      count += 1
    return count

How to count the number of letters in a string with a list of sample? I get nothing in my python shell when I wrote the above code in my python file.

Upvotes: 1

Views: 7249

Answers (4)

jarsever
jarsever

Reputation: 780

First you should probably look at correct indenting and only send in value. Also value is being overwritten so the last one will be the actual reference.

Second you need to call the function that you have defined.

#value = 'bcdjbcdscv'
#value = 'bcdvfdvdfvvdfvv'

value = 'bcvfdvdfvcdjbcdscv'

def count_letters(word, char):
    count = 0
    for c in word:
        if char == c:
        count += 1
    return count

x = count_letters(value, 'b')
print x
# 2

This should produce the result you are looking for. You could also just call:

print value.count('b')
# 2

Upvotes: 1

ultimatetechie
ultimatetechie

Reputation: 354

In python, there is a built-in method to do this. Simply type:

value = 'bcdjbcdscv'    
value.count('c')

Upvotes: 0

zhangxaochen
zhangxaochen

Reputation: 34017

functions need to be called, and the return values need to be printed to the stdout:

In [984]: value = 'bcvfdvdfvcdjbcdscv'

In [985]: count_letters(value, 'b')
Out[985]: 2

In [987]: ds=count_letters(value, 'd') #if you assign the return value to some variable, print it out:

In [988]: print ds
4

EDIT:

On calculating the length of the string, use python builtin function len:

In [1024]: s='abcdefghij'

In [1025]: len(s)
Out[1025]: 10

You'd better google it with some keywords like "python get length of a string" before you ask on SO, it's much time saving :)

EDIT2:

How to calculate the length of several strings with one function call?

use var-positional parameter *args, which accepts an arbitrary sequence of positional arguments:

In [1048]: def get_lengths(*args):
      ...:     return [len(i) for i in args]

In [1049]: get_lengths('abcd', 'efg', '1234567')
Out[1049]: [4, 3, 7]

Upvotes: 2

Kevin
Kevin

Reputation: 2182

There is a built-in method for this:

value.count('c')

Upvotes: 5

Related Questions