Home > OS >  Unique occurrence of period within the list
Unique occurrence of period within the list

Time:01-29

I'm using the textwrap module to split my string into a list with width = 40. Then, I'm trying to iterate through the list and after every 2nd period, type "We hit second period" and then reset the counting. The problem I think I'm having is that if there is multiple periods within the list, my iteration doesn't work. After running the following code I get "We hit second period" twice, instead of 3 times, as we have 6 periods within the list.

import textwrap
text = "We are having a long, long long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do. All day. Long."
unique_character = textwrap.wrap(text, width=40)
x=0
for items in unique_character:
    print(items)
    items.count(".")
    if x == 0:
        x =1
    elif x==1:
        x =1
    elif x ==2:
        print("We hit second period")
    else:
        x=0

CodePudding user response:

You are not using the value items.count(".") returnes. I also created a solution, that doesn't use it, since adding the number of . in a line would not work if we were adding 3 or more at a time.

import textwrap
text = "We are having a long, long long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do. All day. Long."
unique_character = textwrap.wrap(text, width=40)
period_count = 0
for items in unique_character:
    print(items)
    for l in items:
        if l == ".":
            period_count  = 1
            if period_count % 2 == 0 and period_count:
                print("We hit second period")

CodePudding user response:

You need to actually save the result of items.count to a variable, and add it to the accumulator.

import textwrap
text = "We are having a long, long long very long sentence here. Just trying to test if it works. We are trying to test. Testing we do. All day. Long."
unique_character = textwrap.wrap(text, width=40)
accumDots = 0
for line in unique_character:
    print(line)
    dots = line.count(".")
    if accumDots   dots >= 2:
        print("We hit second period")
        accumDots = 0
    else:
        accumDots  = dots
  • Related