How to i extract a substring from a string in Python and store it in a list?

1k views Asked by At

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++ )

1

There are 1 answers

0
Miskov On

string[a:b] is what you're looking for. It gives you the characters between a and b (including a). Knowing that, you have to search for all of the n-substrings starting with 0 and ending with len(your_string) - n + 1 To aim for the elegant and Pythonic solution, read something about:

List Comprehensions

https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions

Good luck!