-4

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

Srivatsa Sinha
  • 193
  • 2
  • 12
  • 3
    Do you have tried anything to solve your problem so far? – Mazdak Jun 09 '15 at 18:48
  • i tried slicing and directly storing it in list, like this a[i]=str[beg:end]... But this gives run time error. I am very new to Python.. Infact in the process of learning.. I have previous experience with C++, and what i tried was a correlation – Srivatsa Sinha Jun 09 '15 at 19:01
  • @SrivatsaSinha if you show your attempt - others can advise you on how to fix it - that shows an effort on your part and will also help you learn – Jon Clements Jun 09 '15 at 19:01
  • Welcome to Stack overflow! This is likely to get closed as it's basically a request for code, without showing what you've already tried. I recommend you edit in what you've tried. You might also like to look at this question http://stackoverflow.com/questions/21303224/iterate-over-all-pairs-of-consecutive-items-from-a-given-list - you can apply the answers there to a string . Good luck! – J Richard Snape Jun 09 '15 at 19:03

1 Answers1

1

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!

Miskov
  • 178
  • 12