Generating All N-tuples From A String
Is there a simple, pythonic, way to generate all n-tuples of a given length from a string? For example, I would like generateTuples('Hello, World!', 3) to produce the following: [
Solution 1:
>>> a = "Hello, World!"
>>> def generate_tuples(string, n):
... return [string[i:i+n] for i in range(len(string)-n+1)]
...
>>> generate_tuples(a, 3)
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
Solution 2:
This is probably what you are looking for
>>> st="Hello, World!"
>>> [st[i:i+3] for i in xrange(0,len(st)-2)]
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
or if you want you can write it as a function:
>>> def generateTuples(st,n):
return [st[i:i+n] for i in xrange(0,len(st)-n+1)]
Solution 3:
>>> text = "Hello, World!"
>>> map(''.join,zip(*(text[i:] for i in range(3))))
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
Solution 4:
>>> text = "Hello, World!"
>>>
>>> def subseqs(seq, length):
... for i in xrange(len(seq) - length + 1):
... yield seq[i:i+length]
...
>>> map(''.join, subseqs(text, 3))
['Hel', 'ell', 'llo', 'lo,', 'o, ', ', W', ' Wo', 'Wor', 'orl', 'rld', 'ld!']
Post a Comment for "Generating All N-tuples From A String"