Count number of commas in a string python

I am dealing with text strings such as the following: LN1 2DW, DN21 5BJ, DN21 5BL, ...

In Python, how can I count the number of elements between commas? Each element can be made of 6, 7, or 8 characters, and in my example there are 3 elements shown. The separator is always a comma.

I have never done anything related to text mining so this would be a start for me.

bad_coder

9,22119 gold badges37 silver badges61 bronze badges

asked Jan 10, 2017 at 14:48

0

You can count the number of commas:

text.count[","] + 1
# 3

answered Jan 10, 2017 at 14:53

PsidomPsidom

200k27 gold badges312 silver badges331 bronze badges

4

If the comma [,] is the separator, you can simply use str.split on the string and then len[..] on the result:

text = 'LN1 2DW, DN21 5BJ, DN21 5B'
number = len[text.split[',']]

You can also reuse the list of elements. For instance:

text = 'LN1 2DW, DN21 5BJ, DN21 5B'
tags = text.split[',']
number = len[tags]
#do something with the `tags`

answered Jan 10, 2017 at 14:50

Willem Van OnsemWillem Van Onsem

409k29 gold badges389 silver badges511 bronze badges

6

Willien and Psidom already mentioned count,

I just wanted to add that in python a string is also iteratable, thus list comprehension could also be applied:

n = len[[c for c in ','+text if c==',']]

Or

n = sum[1 for c in ','+text if c==',']

answered Jan 10, 2017 at 14:59

Uri GorenUri Goren

12.8k6 gold badges54 silver badges103 bronze badges

3

  1. HowTo
  2. Python How-To's
  3. Count Occurrences of a Character in a String in Python

Created: June-02, 2021 | Updated: July-18, 2021

  1. Use the count[] Function to Count the Number of a Characters Occuring in a String in Python
  2. Use the collections.Counter to Count the Occurrences of a Character in a String in Python
  3. Use Regular Expressions to Count the Occurrences of a Character in a String in Python
  4. Use the defaultdict to Count the Occurrences of a Character in a String in Python
  5. Use the pandas.value_counts[] to Count the Occurrences of a Character in a String in Python
  6. Use a lambda Expression to Count the Occurrences of a Character in a String in Python
  7. Use the for Loop to Count the Occurrences of a Character in a String in Python

In Programming, a string is a sequence of characters.

This tutorial will introduce how to count the number of occurrences of a character in a String in Python.

Use the count[] Function to Count the Number of a Characters Occuring in a String in Python

We can count the occurrence of a value in strings using the count[] function. It will return how many times the value appears in the given string.

For example,

print['Mary had a little lamb'.count['a']]

Output:

4

Remember, upper and lower cases are treated as different characters. A and a will be treated as different characters and have different counts.

Use the collections.Counter to Count the Occurrences of a Character in a String in Python

A Counter is a dictionary subclass present in the collections module. It stores the elements as dictionary keys, and their occurrences are stored as dictionary values. Instead of raising an error, it returns a zero count for missing items.

For example,

from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter[my_str]
print[counter['a']]

Output:

4

It is a better choice when counting for many letters as counter calculates all the counts one time. It is a lot faster than the count[] function.

Use Regular Expressions to Count the Occurrences of a Character in a String in Python

A regular expression is a specialized syntax held in a pattern that helps find the strings or set of strings by matching that pattern. We import the re module to work with regular expressions.

We can use the findall[] function for our problem.

For example,

import re
my_string = "Mary had a little lamb"
print[len[re.findall["a", my_string]]]

Output:

4

Use the defaultdict to Count the Occurrences of a Character in a String in Python

Defaultdict is present in the collections module and is derived from the dictionary class. Its functionality is relatively the same as that of dictionaries except that it never raises a KeyError, as it provides a default value for the key that never exists.

We can use it to get the occurrences of a character in a string as shown below.

from collections import defaultdict

text = 'Mary had a little lamb'
chars = defaultdict[int]

for char in text:
    chars[char] += 1
    
print[chars['a']]
print[chars['t']]
print[chars['w']] # element not present in the string, hence print 0

Output:

4
2
0

Use the pandas.value_counts[] to Count the Occurrences of a Character in a String in Python

We can use the pandas.value_counts[] method to get the occurrences of all the characters present in the provided string. We need to pass the string as a Series object.

For example,

import pandas as pd
phrase = "Mary had a little lamb"
print[pd.Series[list[phrase]].value_counts[]]

Output:

     4
a    4
l    3
t    2
e    1
b    1
h    1
r    1
y    1
M    1
m    1
i    1
d    1
dtype: int64

It returns the occurrences of all characters in a Series object.

Use a lambda Expression to Count the Occurrences of a Character in a String in Python

lambda functions can not only count occurrences from the given string, but can also work when we have the string, as a list of sub-strings.

See the following code.

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
print[sum[map[lambda x : 1 if 'a' in x else 0, sentence]]]

Output:

4

Use the for Loop to Count the Occurrences of a Character in a String in Python

We iterate over the string, and if the element equals the desired character, the count variable is incremented till we reach the end of the string.

For example,

sentence = 'Mary had a little lamb'    
count = 0
for i in sentence:
    if i == "a":
        count = count + 1
print[count]

Output:

4

We can see another way of using this method with the sum[] function can be seen below.

my_string = "Mary had a little lamb"
print[sum[char == 'a' for char in my_string]]

Output:

4

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • How do you count the number of commas in a string?

    Select the cell you will place the counting result, type the formula =LEN[A2]-LEN[SUBSTITUTE[A2,",",""]] [A2 is the cell where you will count the commas] into it, and then drag this cell's AutoFill Handle to the range as you need.

    How do you count comma separated strings in Python?

    Python Tuple count[] The python create tuple technique allows placing multiple elements inside a parenthesis separated by commas. The python count method returns the number of times the element specified by the user has been repeated in the tuple.

    How do you count occurrences of a string in Python?

    One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count[] method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

    How do you count the number of substrings in a string in Python?

    The count[] method returns the number of occurrences of a substring in the given string..
    substring - string whose count is to be found..
    start [Optional] - starting index within the string where search starts..
    end [Optional] - ending index within the string where search ends..

    Chủ Đề