mercredi 25 février 2015

Python: Slicing string in three-character substrings

I am attempting to slice a string into triplets based on the characters like this:



string1 = 'abcdef'
substrings = 'abc', 'bcd', 'cde', 'def'


I then want to compare these 'triplets to a second string and count their occurrence:



string2 = 'abcijk'
substrings of string1 in string2 = 1 ('abc').


I am trying to do this using a function:



def HowManyTriplets(s1, s2):
n = 0
for c in s1:
print c + c[:2]
if c in s1 is c in s2:
n = n + 1
return n


This code does not work because c[:2] does not get the two characters following any c (s1[:2] simply appends the first two characters of s1).


How can I solve this to append the two characters that follow a character c to c, for example c = c + d + e


Aucun commentaire:

Enregistrer un commentaire