Reputation: 33
I was working on a couple of things and first off I had to split a string (it was a paragaph) and then take off the punctuation of each string. For that I did the following:
a = string1.split()
print(a)
punc = "?.,!"
a = ["".join(c for c in s if c not in punc) for s in a]
print(a)
After this I have to count how many words end in "ing". I tried various ways but for some reason they always count 0 when they should count 10. This was my latest attempt:
suffix = "ing"
suffix_count = 0
if any (''.endswith(suffix) for s in a):
suffix_count += 1
print ("Found {} words ending in ing".format(suffix_count))
What am I doing wrong?
Upvotes: 2
Views: 2401
Reputation: 180441
There is a much easier way to remove punc and sum using rstrip
so we don't need to loop over every char:
sum(s.rstrip(punc).endswith("ing") for s in a)
So your double loop can be replaced with the following to remove the punc:
a = [s.rstrip(punc) for s in a]
Also using string.punctuation
may be better:
from string import punctuation
a = [s.rstrip(punctuation) for s in a]
Upvotes: 1
Reputation: 399871
You could do:
suffix_count = len([s for s in a if s.endswith(suffix)])
Simply forms the list of all strings that end with the suffix, then computes the length of that list, which is of course the number of strings that ended with the suffix. I think it's cleaner than an explicit for
loop.
Upvotes: 1
Reputation: 94339
Instead of
if any (''.endswith(suffix) for s in a):
suffix_count += 1
try
suffix_count = sum(1 for s in a if s.endswith(suffix))
The issue with your code is that you're checking whether the empty string ends with 'suffix' (which is always false) but even if you got that check right: you're increasing suffix_count just once unrelated to how many strings end in 'suffix'.
Upvotes: 3
Reputation: 5291
try this out:
a = ["singing", "dancing", "playing"]
suffix = "ing"
suffix_count = 0
for s in a:
if s.endswith(suffix):
suffix_count += 1
print ("Found {} words ending in ing".format(suffix_count))
For me it printed 3.
Hope it helps
Upvotes: 0