Question

I am fairly new to all of this programming and Python. So I just had a question regarding the Splicing method.

here is the code:

function(seq, n)
return seq[:n]

It is hard to explain what I want done with it but this is what the output should look like. I am sure u intellegent people will understand.

function([5, 3, 7, 2, 8], 3)

output:

[8, 2, 5, 3, 7]

or

function("ACEJY3529",4)

output:

'3529YACEJ'

Its sort of like swapping positions...

So the problem is that, this code works fine with integers... but when I use strings, it crashes...

Was it helpful?

Solution

The most generic way is to always deal with slices and not individual items, eg:

def function(seq, n):
    return seq[n+1:] + seq[n:n+1] + seq[:n]
                       ^^^^^^^^^^

We always make that a length 1 iterable rather than a non iterable single item.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top