Tom Davidson
Tom Davidson

Reputation: 774

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

Upvotes: 1

Views: 2534

Answers (3)

Savir
Savir

Reputation: 18438

Since you're gonna need to get the substrings for two different strings (your string1 and string2), I'd move that slicing into a very simple function:

def substring(string):
   return [ string[i:i+3] for i in range(len(string)) if i + 3 <= len(string) ]

To compare and count, you can use the list.count method and combine it with your recently created substring function:

string1 = 'abcdef'
string2 = 'abcijk'
[ (substr, substring(string2).count(substr)) for substr in substring(string1) ]

Which outputs:

[('abc', 1), ('bcd', 0), ('cde', 0), ('def', 0)]

Upvotes: 1

Kelvin
Kelvin

Reputation: 1367

Try:

def subs():
    string1 = 'abcdef'
    string2 = 'abcijk'
    subs = [string1[s:s+3] for s in range(len(string1)) if len(string1[s:s+3]) > 2]
    for s in subs:
        print s, string2.count(s)

Upvotes: 2

zehnpaard
zehnpaard

Reputation: 6243

You should be able to just use slice notation in a for-loop:

for i in xrange(len(s1) - 2):
    c = s1[i:i+3]
    # do various operations here with c

Alternatively collect them in a list comprehension:

list1 = [s1[i:i+3] for i in xrange(len(s1) - 2)]
n = 0
for c in list1:
    if c in s2:
        n += 1
print n

Upvotes: 2

Related Questions