Reputation: 443
Is there a way to count the number of lines in a set of text? For example:
text="hello what are you"\
"doing with yourself"\
"this weekend?"
I want to count the "\n". I know I could count this using regular python, but just wondering if there is a way to count this with Regular Expressions?
Upvotes: 0
Views: 3945
Reputation: 5658
you can also use enumerate to count the lines in a file as follows:
with open (file, "r") as fp:
for cnt, _ in enumerate (fp,1):
pass
print(cnt)
Upvotes: 1
Reputation: 2411
Side Note
In your case there is no newline in text
.
Probably you wanted to define
text = """hello what are you
doing with yourself
this weekend?"""
Answer
You don't need a regular expression.
Just use text.count("\n")
~
Edit: Oh, nevermind. You need it to be a regex?
len(re.findall("\n", text))
should work
Upvotes: 2
Reputation: 168626
Yes, you can use regular expressions to count newlines.
Run re.findall()
and count the results.
len(re.findall('\n', text))
For example, on my Linux computer:
In [5]: with open('/etc/passwd') as fp: text = fp.read()
In [6]: len(re.findall('\n', text))
Out[6]: 56
But really, why would you? As you point out, there are already better ways to do it.
Upvotes: 0