I have a string "ababa"
. I want to extract all the substring of length say, 2, and store it in a list like ['ab' , 'ba' , 'ab', 'ba' ]
.
Here is what i have already tried, (I beforehand know that size of string is N):
str = input()
for k in range (N- 2 +1)
sub[k] = str[k:k+2]
But this line of code gives error as the last line is illegal assignment. ( I am new to Python and have tried simply drawing a correlation with C++ )
string[a:b]
is what you're looking for. It gives you the characters betweena
andb
(including a). Knowing that, you have to search for all of the n-substrings starting with 0 and ending withlen(your_string) - n + 1
To aim for the elegant and Pythonic solution, read something about:https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
Good luck!