Count the number of trailing characters at the end of a string ignoring duplicates inside the string?

Question:

I have a series of strings like:

my_text = "one? two three??"

I want to count only the number of ? at the end of the string. The above should return 2 (rather than 3).

What I’ve tried so far:

my_text.count("?") # returns 3
Asked By: Optimus

||

Answers:

There’s not a built-in method for it. But something simple like this should do the trick:

>>> len(my_text) - len(my_text.rstrip('?'))
2
Answered By: wim

You could also use a regexp to count the number of trailing question marks :

import re

def count_trailing_question_marks(text):
    last_question_marks = re.compile("?*$")
    return len(last_question_marks.search(text).group(0))

print count_trailing_question_marks("one? two three??")
# 2
print count_trailing_question_marks("one? two three")
# 0
Answered By: Eric Duminil

Not so clean but simple way:

my_text = "one? two three??"

total = 0
question_mark = '?'
i = 0
for c in my_text:
    i -= 1
    if my_text[i] == question_mark:
        total += 1
    else:
        break
Answered By: Juggernaut

One-liner using my favourite itertools:

First reverse the string, then continue iterating (taking the values) while our condition is satisfied (value == ‘?’). This returns an iterable which we exhaust into a list and finally take its length.

len(list(itertools.takewhile(lambda x_x=='?',reversed(my_text))))
Answered By: pyhelp
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.