'I need to access the current character and the characters that follow, by their index, while looping through a string
So I was just messing around, trying to loop through every single character in a string and picking out patterns forming particular words, instead of using inbuilt functions or split(). I was able to do this in Javascript, but don't understand how to do the same in python. Here is my simple JS program for counting the word 'this' or 'This':
let str1 = "This is a sample string and this is a sample string too. That and this are also sample strings, just like this one";
let count = 0;
for(let i = 0; i < str1.length; i++){
if((str1[i] == 't' || str1[i] == 'T') && str1[i+1] == 'h' && str1[i+2] == 'i' && str1[i+3] == 's'){
count += 1;
}
}
console.log(count); // => 4
Solution 1:[1]
The two language is surprisingly similar,
str1 = "This is a sample string and this is a sample string too. That and this are also sample strings, just like this one";
count = 0
for i in range(len(str1)):
if str1[i].lower() == 't' and str1[i+1] == 'h' and str1[i+2] == 'i' and str1[i+3] == 's':
count += 1
print(count)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ytung-dev |
