Count the number of items in a string, separated by a comma

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

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

I have never done anything related to text mining, so for me this would be the beginning.

+4
source share
3 answers

You can count the number of commas:

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

If the comma ( ,) is a separator, you can simply use str.splitin a string and then len(..)on the result:

text = 'LN1 2DW, DN21 5BJ, DN21 5B'
number = len(text.split(','))

. :

text = 'LN1 2DW, DN21 5BJ, DN21 5B'
tags = text.split(',')
number = len(tags)
#do something with the `tags`
+9

Willian and Psidom already mentioned count,

I just wanted to add that in python the string is also iterative, so list comprehension can also be implemented:

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

or

n = sum(1 for c in ','+text if c==',')
+1
source

Source: https://habr.com/ru/post/1666386/


All Articles