Pergunta

To start I will mention that I am new to the Python Language and come from a networking background. If you are wondering why I am using Python 2.5 it is due to some device constraints.

What I am trying to do is count the number of lines that are in a string of data as seen below. (not in a file)

data = ['This','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\n']

Unfortunately I can't seem to get the correct syntax to count \n. So far this is what I have come up with.

num = data.count('\n')
print num

The above code is clearly wrong for the intended output since it returns 1 in relation to the test data, I would like to see it return 4 if possible. It only finds 1 of the '\n' being the last one in the example since it matches.

If I use the following code instead to find all of them it doesn't run due to syntax.

num = data.count (\n)
print num

I based this code from the following link, the example is the third one down.

http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/strings3.html

Is there anyway of accomplishing this or should I be looking at a different solution?

Any help is appreciated
Thank-you

Foi útil?

Solução

list.count is used to get the count of an item in list, but you need to do a substring search in each item to get the count as 4.

>>> data = ['This','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\nThis','is','some','test','data','\n']

Total number of items that contain '\n':

>>> sum('\n' in item for item in data)
4

Sum of count of all '\n's in data:

>>> data = ['\n\nfoo','\n\n\nbar']
>>> sum(item.count('\n') for item in data)
5

Outras dicas

Your first code does not work because you only have one '\n' in your actual list of strings. When you compare '\n' to something like 'nThis', then it will say that \n is not equal to that string and not include it in the count.

What you can do is join the list into a string like so:

x = ''.join(num)

and then try using the count method of the string class. This will let you find substrings that are equivalent to '\n' in the total string.

y = x.count('\n')
print y
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top