3

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
Optimus
  • 1,354
  • 1
  • 21
  • 40

4 Answers4

9

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
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
wim
  • 338,267
  • 99
  • 616
  • 750
2

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
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124
1

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
Amin Etesamian
  • 3,363
  • 5
  • 27
  • 50
1

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))))
pyhelp
  • 11
  • 1
  • 1