Issue with counting newlines in Python

Viewed 85

I'm having a slight problem with counting newlines. I'm working on a program that's supposed to count items from a .txt file (characters, upper/lowercase characters, etc.). However, my line counter is counting the amount of character plus one instead of the amount of new lines. For instance, instead of getting something like a character count of 1048 and a line count of 37, I get a character count of 1048 and a line count of 1049. I'm not sure where I messed up.

Below is the relevant code. I appreciate any assistance.

# initializing counters
char_count = 0
lower_count = 0
upper_count = 0
lines_count = 0
word_count = 0
prev_ch = ' '
is_prev_alnum = False



for ch in contents:
    char_count += 1
    if ch.islower():
        lower_count += 1
    if ch.isupper():
        upper_count += 1
    if ch == '\n':
        lines_count += 1


    # count words
    if ch.isalnum():
        if not is_prev_alnum:
            word_count += 1
        is_prev_alnum = True
    else:
        is_prev_alnum = False

    if prev_ch != '\n':
        lines_count += 1

    prev_ch = ch 
1 Answers

Why do you have

    if prev_ch != '\n':
        lines_count += 1

Since prev_ch is already defined as ' ' or a valid ch it is not '\n', it keeps counting it for each loop just like the character

As suggested in the comments, you can just do if prev_ch == '\n'

Related