Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find how many lines in string

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) 
like image 370
falcon user Avatar asked Jan 18 '16 02:01

falcon user


People also ask

Does count () work on strings?

Python String count() MethodThe count() method returns the number of times a specified value appears in the string.

How do you count the number of lines in a string Java?

Java For TestersInstantiate a String class by passing the byte array obtained, as a parameter its constructor. Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method. Now, find the length of the obtained array.


2 Answers

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

like image 73
jfs Avatar answered Oct 02 '22 18:10

jfs


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()) 
like image 37
TigerhawkT3 Avatar answered Oct 02 '22 16:10

TigerhawkT3