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

Mathemats
  • 1,185
  • 4
  • 22
  • 35
JGerulskis
  • 800
  • 2
  • 10
  • 24

3 Answers3

24

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.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
14

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]
John1024
  • 109,961
  • 14
  • 137
  • 171
2

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.

Community
  • 1
  • 1
ViennaMike
  • 2,207
  • 1
  • 24
  • 38