JGerulskis
JGerulskis

Reputation: 808

How to count lines in multi lined strings

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).

Upvotes: 7

Views: 28831

Answers (3)

ViennaMike
ViennaMike

Reputation: 2337

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.

Upvotes: 2

John1024
John1024

Reputation: 113994

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]

Upvotes: 14

Christian Tapia
Christian Tapia

Reputation: 34186

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.

Upvotes: 24

Related Questions