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
There is no built-in method. But something simple like this should do the trick:
>>> len(my_text) - len(my_text.rstrip('?')) 2
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
, :
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
itertools:
, ( ), (value == '?'). , , , .
len(list(itertools.takewhile(lambda x:x=='?',reversed(my_text))))
Source: https://habr.com/ru/post/1669466/More articles:AngularJS React Date Filter - angularjsHow to configure Travis CI and postgresql using custom db credentials? - travis-ciWhat is an artist pattern in a C ++ context? - c ++Request temporary peaks how to find a bottleneck - javaWhy does a skalak cause a "divergent implicit expansion" error? - scalaНеожиданный импорт токена с помощью React.NET - c#Which one is a bubble or both of them? - cIntroducing From by attribute that has Self as a member - traitsHow can I create a class diagram for F #? - visual-studioValidating a variable before calling the super constructor - javaAll Articles