Count the number of elements in a string separated by comma

FaCoffee picture FaCoffee · Jan 10, 2017 · Viewed 25.6k times · Source

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.

Answer

Psidom picture Psidom · Jan 10, 2017

You can count the number of commas:

text.count(",") + 1
# 3