Find how many lines in string

Question:

I am creating a python movie player/maker, and I want to find the number of lines in a multiple line string. I was wondering if there was any built in function or function I could code to do this:

x = """
line1
line2 """

getLines(x)
Asked By: falcon user

||

Answers:

You can do:

len(x.split('n'))
Answered By: heemayl

You can split() it and find the length of the resulting list:

length = len(x.split('n'))

Or you can count() the number of newline characters:

length = x.count('n')

Or you can use splitlines() and find the length of the resulting list:

length = len(x.splitlines())
Answered By: TigerhawkT3

If newline is 'n' then nlines = x.count('n').

The advantage is that you don’t need to create an unnecessary list as .split('n') does (the result may differ depending on x.endswith('n')).

str.splitlines() accepts more characters as newlines: nlines = len(x.splitlines()).

Answered By: jfs

SPAMnEGGSnBEANS = Three lines, two line breaks

So if counting lines, use + 1, or you’ll make a fencepost error:

x.count( "n" ) + 1
Answered By: c z
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.