Home > Back-end >  How to print first nth characters from a string then first n 1 characters and so on
How to print first nth characters from a string then first n 1 characters and so on

Time:03-13

This is what I have so far:

def generateCosets(str, n):
    equalStr = []
    for i in range(0, n):
        part = getNthLetters(str, n)
        equalStr.append(part)
    return equalStr


def getNthLetters(text, n):
    builtstring = ''
    for i in range(0, len(text)):
        if i % n == 0:
            builtstring = builtstring   text[i]
    return builtstring

If I run this code:

s0 = '12345678'
myArr = generateCosets(s0,2)
print(myArr[0], myArr[1])

it yields:

1357 1357

instead of:

1357 2468

I just don't know how to make the for loop start from i 1 every time I use the getNthLetters method

CodePudding user response:

you can use slicing on string

s0[0::2]
'1357'
s0[1::2]
'2468'

CodePudding user response:

You can solve this problem by checking the parity of the indexes at your initial string:

s0 = '12345678'
print(''.join([i if int(i)%2 != 0 else "" for i in s0]), ''.join([i if int(i)%2 == 0 else "" for i in s0]))

CodePudding user response:

You can use slice notation (check Understanding slice notation) with step:

def generate_cosets(text, n):
    for i in range(n):
        yield text[i::n]

Usage:

s0 = '12345678'
print(*generate_cosets(s0, 2))

You can help my country, check my profile info.

  • Related