48

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)
falcon user
  • 717
  • 1
  • 6
  • 10
  • 2
    And in this case, the output should be 3? – Remi Guan Jan 18 '16 at 02:34
  • 1
    Possible duplicate of [How to count lines in multi lined strings](http://stackoverflow.com/questions/28802417/how-to-count-lines-in-multi-lined-strings) – Nirmal Feb 13 '17 at 09:31
  • ``` x.count(os.linesep)+1 ``` https://stackoverflow.com/questions/3821784/whats-the-difference-between-n-and-r-n – Simon Leary Dec 11 '22 at 18:49

4 Answers4

71

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

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 2
    `str.splitlines()` also won't include the final line break/empty line (if any), which is often the preferred behavior. Example: `text = """line1 line2 {empty line}""" print(text.split('\n')) print(text.splitlines())` Result: `['line1', 'line2', ''] ['line1', 'line2']` – Marco Roy Jan 07 '20 at 22:20
15

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())
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
8

SPAM\nEGGS\nBEANS = Three lines, two line breaks

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

x.count( "\n" ) + 1
c z
  • 7,726
  • 3
  • 46
  • 59
2

You can do:

len(x.split('\n'))
heemayl
  • 39,294
  • 7
  • 70
  • 76