1

For some reason after the second loop in my array the code is skipping a character for some reason.

I think here is the problem:

    for word in range(int(len(ShortArray))):
        localString = LongArray[word]
        #print(word)
        if localString[:2] == ShortArray[word]:
            print(LongArray[word])
            print(word)

Here is the full code:

kleuren = ["Rood","Geel","Groen","Blauw","Wit","Paars","Oranje","Zwart"]
KleurenShort = []

def splitArray(string):
    for lenght in range(int(len(string) / 2)):
        KleurenShort.append(string[:2])
        print(KleurenShort)
        string = string.strip(string[:2])
    return KleurenShort

def tekst_naar_kleur(string):
    return 0


def matchFirst2Letters(ShortArray,LongArray):
    for word in range(int(len(ShortArray))):
        localString = LongArray[word]
        #print(word)
        if localString[:2] == ShortArray[word]:
            print(LongArray[word])
            print(word)

matchFirst2Letters(splitArray("RoGeGrBl"),kleuren)

The outcome is:

['Ro']
['Ro', 'Ge']
['Ro', 'Ge', 'rB']
['Ro', 'Ge', 'rB', 'l']

when it should be:

['Ro']
['Ro', 'Ge']
['Ro', 'Ge', 'Gr']
['Ro', 'Ge', 'Gr', 'Bl']

1 Answers1

4

The problem is the use of the string.strip() method.

'aaaaaabcdb'.strip('ab')

gives 'cd' as every instance of 'a' and 'b' in your input string is removed. You can simply get rid of the first two letters of the input string by indexing:

'abcde'[2:] will give 'cde'.

Implemented in your code the corrected version is:

kleuren = ["Rood","Geel","Groen","Blauw","Wit","Paars","Oranje","Zwart"]
KleurenShort = []

def splitArray(string):
    for lenght in range(int(len(string) / 2)):
        KleurenShort.append(string[:2])
        print(KleurenShort)
        string = string[2:]
    return KleurenShort

def tekst_naar_kleur(string):
    return 0


def matchFirst2Letters(ShortArray,LongArray):
    for word in range(int(len(ShortArray))):
        localString = LongArray[word]
        #print(word)
        if localString[:2] == ShortArray[word]:
            print(LongArray[word])
            print(word)

matchFirst2Letters(splitArray("RoGeGrBl"),kleuren)

which outputs

['Ro']
['Ro', 'Ge']
['Ro', 'Ge', 'Gr']
['Ro', 'Ge', 'Gr', 'Bl']
Rood
0
Geel
1
Groen
2
Blauw
3

With the answer from the comment linked below, your splitArray function simply becomes:

def splitArray(string):
    return [string[i:i+2] for i in range(0, len(string), 2)]
Dschoni
  • 3,714
  • 6
  • 45
  • 80
  • Also see https://stackoverflow.com/questions/9475241/split-string-every-nth-character for a easier and faster version of how to split a string into pairs of 2. – Dschoni Jan 19 '21 at 13:49