python – Find how many lines in string
python – Find how many lines in string
If newline is n
then nlines = x.count(n)
.
The advantage is that you dont 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())
.
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())
python – Find how many lines in string
SPAMnEGGSnBEANS
= Three lines, two line breaks
So if counting lines, use + 1, or youll make a fencepost error:
x.count( n ) + 1