Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count lines in multi lined strings

Tags:

python-3.x

Level ="""
            aaaaaa
            awawa"""

I'm wondering how do you count the lines of a multi lined string in python.

Also once you've counted those lines how do you count how many letters are in that line. I'd assume to do this part you'd do len(line_of_string).

like image 596
JGerulskis Avatar asked Mar 02 '15 03:03

JGerulskis


3 Answers

You can count the number of the new-line character occurrences:

Level.count('\n') # in your example, this would return `2`

and add 1 to the result.

like image 85
Christian Tapia Avatar answered Sep 20 '22 07:09

Christian Tapia


Let's define this multi-line string:

>>> level="""one
... two
... three"""

To count the number of lines in it:

>>> len(level.split('\n'))
3

To find the length of each of those lines:

>>> [len(line) for line in level.split('\n')]
[3, 3, 5]
like image 37
John1024 Avatar answered Sep 21 '22 07:09

John1024


See Count occurrence of a character in a string for the answer on how to count any character, including a new line. For your example, Level.count('\n') and add one.

I'd suggest then splitting on the new line and getting lengths of each string, but there are undoubtedly other ways:

lineList = Level.split('\n')

Then you can get the length of each using len for each item in the list.

like image 27
ViennaMike Avatar answered Sep 20 '22 07:09

ViennaMike