I am trying to search for the sum of occurances of a substring within a string:
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string)):
print(string[i:len(substring)]
I am unsure why this is my output:
ABC
BC
C
Should'nt it be:
ABC
BCD
CDC
DCD
CDC
CodePudding user response:
You need to increment length i times to match len 3 elemnst see
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string)):
print(f'{i} to {len(sub_string)}')
in your case #
0 to 3
1 to 3
2 to 3
3 to 3
Code correction
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string)):
print(string[ i:i len(substring)]
print(f'{i} to {i len(sub_string)}')
output #
0 to 3
1 to 4
2 to 5
3 to 6
you will get
ABC
BCD
CDC
DCD
CodePudding user response:
A small change would get the expected output
Code:
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string)):
print(string[i: i len(sub_string)])
Output
ABC
BCD
CDC
DCD
Reason:
You can try priniting the len(sub_string) and see that it is constanlt 3 because length is always 3.
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string)):
print(i, len(sub_string))
Output:
0 3
1 3
2 3
3 3
The change that we did was i len(sub_string) we are changing the end index by adding it to the start index
CodePudding user response:
You are using len(substring)
instead of i len(substring)
.
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string) 1):
print(string[i:i len(sub_string)])
output:
ABC
BCD
CDC
DCD
CDC
PS: use range(len(string)-len(sub_string) 1)
to make the loop iterate over all possible, including the final index.
CodePudding user response:
You have missed two things when you pass a number in range() it is exclusive of that number so for that you should add 1 to that and you have missed to add i in iteration while slicing this code will work for you.
string = 'ABCDCDC'
sub_string = 'CDC'
for i in range(len(string)-len(sub_string) 1):
print(string[i: i len(sub_string)])