简体   繁体   中英

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.

为此有一个内置方法:

value.count('c')

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]

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM