Question

Below should be a fairly easy counting/length need however I can't work out how to get it working...

Example code

tl1 = "2, 5, 11"
tl2 = "2, 5, 11, 29, 48, 1, 492, 2993, 91, 8, 8, 3"
tl3 = "9382938238"
print len(tl1)
print len(tl2)
print len(tl3)

What it returns:

8
43
1

What it should (for me) return::

3
12
1

Any idea how to achieve the return that I wanted?

Thanks
- Hyflex

Était-ce utile?

La solution

Your problem is that in a string, spaces and characters count in the length.

So, the length of this variable, which is a string:

string = '123 abc'

is 7, because the space counts.

Now, to get the result you are looking for, you need to change the string to a list, which is a group of comma separated values. Note that we don't name our list 'list', because list() is a function in python:

lst = ['2','5','11']

Now, when we check the length of our list:

>>> print len(lst)
3

And we get '3' as the result

To get your string to look like the list above:

>>> tl1 = "2, 5, 11"
>>> print tl1.split(',')
['2','5','11']

Then you could check the length using len()

Autres conseils

The length of string is the number of characters in the string.

Use str.split with comma(','):

>>> tl1 = "2, 5, 11"
>>> tl2 = "2, 5, 11, 29, 48, 1, 492, 2993, 91, 8, 8, 3"
>>> tl3 = "9382938238"

>>> tl1.split(',')
['2', ' 5', ' 11']

>>> len(tl1.split(','))
3
>>> len(tl2.split(','))
12
>>> len(tl3.split(','))
1

You can do this pretty easily with regular expressions:

>> import re
>> result = re.split(r'\D+', '1, 2, 35')
>> result
   ['1', '2', '35']
>> len(result)
   3

If you need to support floating point numbers or something else, it is a bit more complicated, but regular expressions are still the way to go.

If all of your strings are like that, then you can simply use the .split method of a string:

>>> tl1 = "2, 5, 11"
>>> tl2 = "2, 5, 11, 29, 48, 1, 492, 2993, 91, 8, 8, 3"
>>> tl3 = "9382938238"
>>> len(tl1.split())
3
>>> len(tl2.split())
12
>>> len(tl3.split())
1
>>>

.split defaults to split on whitespace characters. You could also split on , if there is a chance that there could be more than 1 space between the numbers.

Here is a way:

tl1 = "2, 5, 11"
tl2 = "2, 5, 11, 29, 48, 1, 492, 2993, 91, 8, 8, 3"
tl3 = "9382938238"

for t in (tl1,tl2,tl3):
    print len([x for x in t.split(',') if x.strip().isdigit()])

Prints:

3
12
1

The advantage is this counts the actual integers, not just the number of split items:

>>> tl4 = '1, 2, a, b, 3, 44'   # 4 numbers, 5 commas, 6 items (numbers and letters)
>>> len(tl4.split(','))
6                               # that numbers and letters...
>>> len([x for x in tl4.split(',') if x.strip().isdigit()])
4                               # integer fields only
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top