How to count the number of a specific character at the end of a line, ignoring duplicates?

I have a series of lines like:

my_text = "one? two three??"

I want to count only a number? at the end of the line. The above should return 2 (not 3).

What I have tried so far:

my_text.count("?") # returns 3
+4
source share
4 answers

There is no built-in method. But something simple like this should do the trick:

>>> len(my_text) - len(my_text.rstrip('?'))
2
+9
source

You can also use regular expression to count the number of backward 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
+1
source

, :

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
0

itertools:

, ( ), (value == '?'). , , , .

len(list(itertools.takewhile(lambda x:x=='?',reversed(my_text))))
0

Source: https://habr.com/ru/post/1669466/


All Articles