I have a string that has comma separated values. How can I count how many elements in the string separated by comma? e.g following string has 4 elements
string = "1,2,3,4";
count() method, and the String. length() method. You can count characters from strings, including spaces, without spaces, and the occurrence of the specific character in a string by using these methods. This tutorial discussed the methods to count characters in a string in Java.
Conclusion: Count() is a Python built-in function that returns the number of times an object appears in a list. The count() method is one of Python's built-in functions. It returns the number of times a given value occurs in a string or a list, as the name implies.
Using Len() function to Get the Number of Elements We can use the len( ) function to return the number of elements present in the list.
Python String count() The count() method returns the number of occurrences of a substring in the given string.
All of the answers suggesting something equivalent to myString.split(',').length
could lead to incorrect results because:
"".split(',').length == 1
An empty string is not what you may want to consider a list of 1 item.
A more intuitive, yet still succinct implementation would be:
myString.split(',').filter((i) => i.length).length
This doesn't consider 0-character strings as elements in the list.
"".split(',').filter((i) => i.length).length
0
"1".split(',').filter((i) => i.length).length
1
"1,2,3".split(',').filter((i) => i.length).length
3
",,,,,".split(',').filter((i) => i.length).length
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With