2

Hey guys I have a simple question.

How do I slice a string of any length into equal parts

ie AGTTGTCGAGGTTGCGATTTATTGGGTGCGAGT by 3 into

AGT TGT CGA GGT TGC GAT TTA TTG GGT GCG AGT

?

Deaven Morris
  • 107
  • 1
  • 3
  • 13
  • 2
    FYI, in programming jargon slicing would be picking a range and discarding the rest (e.g. "take the third through sixth element"). What you describe is more commonly called splitting. –  May 04 '13 at 15:44

1 Answers1

1
>>> s = 'AGTTGTCGAGGTTGCGATTTATTGGGTGCGAGT'
>>> n = 3
>>> [s[i:i+n] for i in xrange(0, len(s), n)]
['AGT', 'TGT', 'CGA', 'GGT', 'TGC', 'GAT', 'TTA', 'TTG', 'GGT', 'GCG', 'AGT']
arshajii
  • 127,459
  • 24
  • 238
  • 287
  • `NameError: name 'xrange' is not defined` – Oleh Prypin May 04 '13 at 15:48
  • Can I do it without forming a list though, I've already done this other way. My problem is I need to translate the sections of 3 into 1 letter chunks next. – Deaven Morris May 04 '13 at 15:49
  • 5
    @BlaXpirit: did you seriously just downvote an answer because it was Python 2? – DSM May 04 '13 at 15:49
  • @DeavenMorris What structure do you want to hold the result in, if not a list? Do you want a generator? – arshajii May 04 '13 at 15:50
  • I need to take user input of length infinity and return it in chuncks of 3. – Deaven Morris May 04 '13 at 15:51
  • @ARS I would like it to be translatable. – Deaven Morris May 04 '13 at 15:52
  • I just need it to recognize that the first 3 letters should be translated to one letter and the next 3 letters should be translated to a different letter etc. – Deaven Morris May 04 '13 at 15:57
  • The question isnt duplicate and I can't find the answer anywhere – Deaven Morris May 05 '13 at 01:25
  • Is it not possible to have python convert string of length 3 into a string of length 1, or do that over an entire list,\. – Deaven Morris May 05 '13 at 01:26
  • @DeavenMorris: That's pretty simple. If you have a list of 3-letter strings and a `dict` of translations, you can use `map(lambda item: translations[item], list_of_three_letter_strings)`. In fact, you can change this answer's list comprehension to a generator comprehension by changing the outer `[` and `]` to `(` and `)` and then it'll work on infinite lists. – icktoofay May 05 '13 at 01:56