# Program to count substrings with all 1s in binary string in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have a binary string s. We have to find the number of substrings that contain only "1"s. If the answer is too large, mod the result by 10^9+7.

So, if the input is like s = "100111", then the output will be 7, because the substrings containing only "1"s are ["1", "1", "1", "1", "11", "11" and "111"]

To solve this, we will follow these steps −

• a := 0
• count := 0
• for i in range 0 to size of s - 1, do
• if s[i] is same as "0", then
• a := 0
• otherwise,
• a := a + 1
• count := count + a
• return count

## Example

Let us see the following implementation to get better understanding −

def solve(s):
a = 0
count = 0
for i in range(len(s)):
if s[i] == "0":
a = 0
else:
a += 1
count += a
return count

s = "100111"
print(solve(s))

## Input

"100111"

## Output

7