1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can I wrap a string or an array around and slice the wrapped string or array in...

Discussão em 'Python' iniciado por Stack, Setembro 18, 2025.

  1. Stack

    Stack Membro Participativo

    How can I slice a string or an array from a point to another point with an end between them?

    Essentially, we want to do something like this,

    n = whatever we want
    print(string[n-5:n+6])


    The above code may look normal. But it doesn't work near the edges (near the beginning of the string/array or the end of the string/array). Because Python's slicing doesn't allow slicing through the end of the array and continuing from the beginning. What if n is smaller than 5 or length of string longer than n+6?

    Here's a better example, consider that we have

    array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']


    We want to print an element with its nearest two neighbors in string for all elements in an array

    print("Two neighbors:")
    for i, x in enumerate(array):
    print(array[i-1] + array + array[(i+1)%len(array)])


    Output:

    Two neighbors:
    kab
    abc
    bcd
    cde
    def
    efg
    fgh
    ghi
    hij
    ijk
    jka


    So far so good, let's do it with four neighbors.

    print("Four neighbors:")
    for i, x in enumerate(array):
    print(array[i-2] + array[i-1] + array + array[(i+1)%len(array)] + array[(i+2)%len(array)])


    Output:

    Four neighbors:
    jkabc
    kabcd
    abcde
    bcdef
    cdefg
    defgh
    efghi
    fghij
    ghijk
    hijka
    ijkab


    You can see where this is going, as the desired number of neighbors grow, the number of times we must type them out one by one increases.

    Is there a way instead of s[n-3]+s[n-2]+s[n-1]+s[n]+s[n+1]+s[n+2]+s[n+3], we can do something like s[n-3:n+4]?

    Note that s[n-3:n]+s[n:(n+4)%len(s)] doesn't work at the edges.

    NOTE:

    For the particular example above, it is possible to do a 3*array or add a number of elements to the front and to the back to essentially "pad" it.

    However, this type of answer cost a bit of memory AND cannot work when we want to wrap it many folds around.

    Consider the following,

    # len(string) = 10
    # n = 0 or any number we want
    print(string[n-499:n+999])


    If the start and end indices can be flexible instead of mirroring each other(eg. string[n-2:n+9] instead of string[n-3:n+4]), it is even better.

    Continue reading...

Compartilhe esta Página