To count the number of lines in a string, the easiest way is to use split() and split the line with the newline character. Then use len()

string = "This is anstring withnnewline in it"

count = len(string.split("n"))

print(string.split("n"))
print(count)

#Output:
["This is a", "string with", "newline in it"]
3

You can also use the split() function from the regular expression module re.

import re

string = "This is anstring withnnewline in it"

count = len(re.split("n", string))

print(re.split("n", string))
print(count)

#Output:
["This is a", "string with", "newline in it"]
3

When working with strings and text in Python, the ability to manipulate and create new objects from strings can be useful.

One such situation is if you have newline characters in your string and want to know how many lines your string contains.

You can find out how many lines your string contains by splitting the string by the newline character and using the len() function to get the count of items returned by split().

Below is a simple example showing you how to get the number of lines in a string using Python.

string = "This is anstring withnnewline in it"

count = len(string.split("n"))

print(string.split("n"))
print(count)

#Output:
["This is a", "string with", "newline in it"]
3

Hopefully this article has been useful for you to learn how to get the number of lines in a string using Python.

Categorized in:

Python,

Last Update: March 11, 2024