Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of elements in a string separated by comma

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.

like image 853
FaCoffee Avatar asked Jan 10 '17 14:01

FaCoffee


People also ask

How can I count the number of comma separated values in a string?

SQL Pattern: How can I count the number of comma separated values in a string? Basically, you replace all occurrences of , with an empty string "" , then subtract its LENGTH from the LENGTH of the unadulterated string, which gives you the number of , characters.


1 Answers

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`
like image 156
Willem Van Onsem Avatar answered Sep 30 '22 11:09

Willem Van Onsem