Python count multiple characters in string

I'm trying to count the letter's 'l' and 'o' in the string below. It seems to work if i count one letter, but as soon as i count the next letter 'o' the string does not add to the total count. What am I missing?

s = "hello world"

print s.count('l' and 'o')

Output: 5

asked Sep 5, 2015 at 14:30

0

You probably mean s.count('l') + s.count('o').

The code you've pasted is equal to s.count('o'): the and operator checks if its first operand (in this case l) is false. If it is false, it returns its first operand (l), but it isn't, so it returns the second operand (o).

>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> True and 'x'
'x'
>>> False and 'x'
False
>>> 'x' and True
True
>>> 'x' and False
False
>>> 'x' and 'y'
'y'
>>> 'l' and 'o'
'o'
>>> s.count('l' and 'o')
2
>>> s.count('o')
2
>>> s.count('l') + s.count('o')
5

Official documentation

answered Sep 5, 2015 at 14:32

Wander NautaWander Nauta

17.5k1 gold badge42 silver badges60 bronze badges

2

Use regular expression:

>>> import re
>>> len(re.findall('[lo]', "hello world"))
5

or map:

>>> sum(map(s.count, ['l','o']))
5

answered Sep 5, 2015 at 14:56

CT ZhuCT Zhu

50.2k17 gold badges114 silver badges131 bronze badges

1

Alternatively, and since you are counting appearances of multiple letters in a given string, use collections.Counter:

>>> from collections import Counter
>>>
>>> s = "hello world"
>>> c = Counter(s)
>>> c["l"] + c["o"]
5

Note that s.count('l' and 'o') that you are currently using would evaluate as s.count('o'):

The expression x and y first evaluates x: if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

In other words:

>>> 'l' and 'o'
'o'

answered Sep 5, 2015 at 14:33

Python count multiple characters in string

alecxealecxe

448k114 gold badges1038 silver badges1164 bronze badges

1

Count all letters in s:

answer = {i: s.count(i) for i in s}

Then sum any keys (letters) from s:

print(answer['l'] + answer['o'])

Tomerikoo

16.6k15 gold badges38 silver badges54 bronze badges

answered Dec 16, 2021 at 13:31

1

In this article we will discuss different ways to count occurrences of a single character or some selected characters in a string and find their index positions in the string.

In Python the String class contains a method to count to the occurrences of a character or string in the string object i.e.

string.count(s, sub[, start[, end]])

It looks for the character or string s in range start to end and returns it’s occurrence count. If start & end is not provided then it will look in complete string and return the occurrence count of s ( character or string) in the main string. Let’s use string.count() to count the occurrences of character ‘s’ in a big string i.e.

mainStr = 'This is a sample string and a sample code. It is very Short.'

# string.count() returns the occurrence count of given character in the string
frequency = mainStr.count('s')

print("Occurrence Count of character 's' : " , frequency)

Output:

Occurrence Count of character 's' :  6

Count Occurrences of a single character in a String using collections.Counter()

collections.counter(iterable-or-mapping)

Counter is a dict subclass and collections.Counter() accepts an iterable entity as argument and keeps the elements in it as keys and their frequency as value. So, if we pass a string in collections.Counter() then it will return a Counter class object which internally has characters as keys and their frequency in string as values. Let’s use that to find the occurrence count of character ‘s’ in a string i.e.

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Counter is a dict sub class that keeps the characters in string as keys and their frequency as value
frequency = Counter(mainStr)['s']

print("Occurrence Count of character 's' : ", frequency)

Output:

Occurrence Count of character 's' :  6

Counter() returned a Counter class ( sub-class of dict) object containing all characters in string as key and their occurrence count as value. We fetched the occurrence count of character ‘s’ from it using [] operator.

Python Regex : Count occurrences of a single character using regex

We can also find the frequency of a character in string using python regex i.e.

# Create a regex pattern to match character 's'
regexPattern = re.compile('s')

# Get a list of characters that matches the regex pattern
listOfmatches = regexPattern.findall(mainStr)

print("Occurrence Count of character 's' : ", len(listOfmatches))

Output:

Occurrence Count of character 's' :  6

We created a regex pattern to match the character ‘s’ and the find all occurrences of character that matched our pattern i.e. all occurrences of character ‘s’ as list. It’s length gives us the occurrence count of character ‘s’ in string.

Using python regex for this is kind of over kill but it is really useful if we are looking to count the occurrences of multiple characters in a string.

Advertisements

Count occurrences of multiple characters in string using Python regex

We will create a regex pattern to match the either character ‘s’ or ‘c’ and the find all occurrences of characters that matched our pattern i.e. all occurrences of either character ‘s’ & ‘c’ as list. It’s length gives us the occurrence count of both the characters in the string. For example,

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Create a regex pattern to match either character 's' or 'c'
regexPattern = re.compile('[sc]')

# Find all characters in a string that maches the given pattern
listOfmatches = regexPattern.findall(mainStr)
print('List of mached characters : ', listOfmatches)
print("Total Occurrence Count of character 's' & 'c' : ", len(listOfmatches))
print("Occurrence Count of character 's' : ", listOfmatches.count('s'))
print("Occurrence Count of character 'c' : ", listOfmatches.count('c'))

Output:

List of mached characters :  ['s', 's', 's', 's', 's', 'c', 's']
Total Occurrence Count of character 's' & 'c' :  7
Occurrence Count of character 's' :  6
Occurrence Count of character 'c' :  1

Finding index positions of single or multiple characters in a string

Count Occurrences and find all index position of a single character in a String

To find the index positions of a given character in string using regex, create a regex pattern to match the character. Then iterate over all the matches of that pattern in the string and add their index positions to a list i.e.

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Create a regex pattern to match character 's'
regexPattern = re.compile('s')

# Iterate over all the matches of regex pattern
iteratorOfMatchObs = regexPattern.finditer(mainStr)
indexPositions = []
count = 0
for matchObj in iteratorOfMatchObs:
    indexPositions.append(matchObj.start())
    count = count + 1

print("Occurrence Count of character 's' : ", count)
print("Index Positions of 's' are : ", indexPositions)

Output

Occurrence Count of character 's' :  6
Index Positions of 's' are :  [3, 6, 10, 17, 30, 47]

Find Occurrence count and index position of a multiple character in a String

Similarly we can find the index positions of multiple characters in the string i.e.

mainStr = 'This is a sample string and a sample code. It is very Short.'

# Create a regex pattern to match character 's' or 'a' or 'c'
regexPattern = re.compile('[sac]')

# Iterate over all the matches of regex pattern
iteratorOfMatchObs = regexPattern.finditer(mainStr)
count = 0
indexPositions = {}
for matchObj in iteratorOfMatchObs:
    indexPositions[matchObj.group()] = indexPositions.get(matchObj.group(), []) + [matchObj.start()]
    count = count + 1

print("Total Occurrence Count of characters 's' , 'a' and 'c' are : ", count)
for (key, value) in indexPositions.items():
    print('Index Positions of ', key , ' are : ', indexPositions[key])

Output:

Total Occurrence Count of characters 's' , 'a' and 'c' are :  12
Index Positions of  s  are :  [3, 6, 10, 17, 30, 47]
Index Positions of  a  are :  [8, 11, 24, 28, 31]
Index Positions of  c  are :  [37]

Complete example is as follows,

from collections import Counter
import re

def main():

   print('**** Count Occurrences of a single character in a String using string.count() **** ')
   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # string.count() returns the occurrence count of given character in the string
   frequency = mainStr.count('s')

   print("Occurrence Count of character 's' : " , frequency)

   print('**** Count Occurrences of a single character in a String using collections.Counter() **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Counter is a dict sub class that keeps the characters in string as keys and their frequency as value
   frequency = Counter(mainStr)['s']

   print("Occurrence Count of character 's' : ", frequency)

   print('**** Count Occurrences of a single character in a String using Regex **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match character 's'
   regexPattern = re.compile('s')

   # Get a list of characters that matches the regex pattern
   listOfmatches = regexPattern.findall(mainStr)

   print("Occurrence Count of character 's' : ", len(listOfmatches))

   print('**** Count Occurrences of multiple characters in a String using Regex **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match either character 's' or 'c'
   regexPattern = re.compile('[sc]')

   # Find all characters in a string that maches the given pattern
   listOfmatches = regexPattern.findall(mainStr)
   print('List of mached characters : ', listOfmatches)
   print("Total Occurrence Count of character 's' & 'c' : ", len(listOfmatches))
   print("Occurrence Count of character 's' : ", listOfmatches.count('s'))
   print("Occurrence Count of character 'c' : ", listOfmatches.count('c'))

   print('**** Count Occurrences and find all index position of a single character in a String **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match character 's'
   regexPattern = re.compile('s')

   # Iterate over all the matches of regex pattern
   iteratorOfMatchObs = regexPattern.finditer(mainStr)
   indexPositions = []
   count = 0
   for matchObj in iteratorOfMatchObs:
       indexPositions.append(matchObj.start())
       count = count + 1

   print("Occurrence Count of character 's' : ", count)
   print("Index Positions of 's' are : ", indexPositions)

   print('**** Find Occurrence count and index position of a multiple character in a String **** ')

   mainStr = 'This is a sample string and a sample code. It is very Short.'

   # Create a regex pattern to match character 's' or 'a' or 'c'
   regexPattern = re.compile('[sac]')

   # Iterate over all the matches of regex pattern
   iteratorOfMatchObs = regexPattern.finditer(mainStr)
   count = 0
   indexPositions = {}
   for matchObj in iteratorOfMatchObs:
       indexPositions[matchObj.group()] = indexPositions.get(matchObj.group(), []) + [matchObj.start()]
       count = count + 1

   print("Total Occurrence Count of characters 's' , 'a' and 'c' are : ", count)
   for (key, value) in indexPositions.items():
       print('Index Positions of ', key , ' are : ', indexPositions[key])



if __name__ == '__main__':
  main()

Output:

**** Count Occurrences of a single character in a String using string.count() **** 
Occurrence Count of character 's' :  6
**** Count Occurrences of a single character in a String using collections.Counter() **** 
Occurrence Count of character 's' :  6
**** Count Occurrences of a single character in a String using Regex **** 
Occurrence Count of character 's' :  6
**** Count Occurrences of multiple characters in a String using Regex **** 
List of mached characters :  ['s', 's', 's', 's', 's', 'c', 's']
Total Occurrence Count of character 's' & 'c' :  7
Occurrence Count of character 's' :  6
Occurrence Count of character 'c' :  1
**** Count Occurrences and find all index position of a single character in a String **** 
Occurrence Count of character 's' :  6
Index Positions of 's' are :  [3, 6, 10, 17, 30, 47]
**** Find Occurrence count and index position of a multiple character in a String **** 
Total Occurrence Count of characters 's' , 'a' and 'c' are :  12
Index Positions of  s  are :  [3, 6, 10, 17, 30, 47]
Index Positions of  a  are :  [8, 11, 24, 28, 31]
Index Positions of  c  are :  [37]

 

How do you count multiple letters in a string in Python?

count('l') + s. count('o') . The code you've pasted is equal to s. count('o') : the and operator checks if its first operand (in this case l ) is false.

How do you count occurrences of multiple characters in a string?

Approach:.
Find the occurrences of character 'a' in the given string..
Find the No. of repetitions which are required to find the 'a' occurrences..
Multiply the single string occurrences to the No. ... .
If given n is not the multiple of given string size then we will find the 'a' occurrences in the remaining substring..

How do you count characters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .

How do you count multiple items in a list Python?

If you want to count multiple items in a list, you can call count() in a loop. This approach, however, requires a separate pass over the list for every count() call; which can be catastrophic for performance. Use couter() method from class collections , instead.