1

This is essentially what I'm trying to do:

myString = '123456789'
slice = myString[-1:1]
*Output = '91'*

However, slicing in Python doesn't appear to work that way. In my problem, the string is representing a circular array, so I need to be able to slice parts of it out without regard for their position in the string (i.e., the first and last elements are 'next to' each other).

  • Are you trying to get 91 as your result or 2345678? If it is 91 myString[-1]+myString[0] would do the trick. And what do you mean by a circular array? Can you give an example? – Sinan Kurmus Mar 02 '20 at 23:30
  • He means 123456789 could be represent as 345678912 or 789123456 and so on. So [-2:5] would be 891234 – Gryu Mar 02 '20 at 23:44
  • Please add your expected output to the question. – Harshal Parekh Mar 02 '20 at 23:55
  • 1
    @Gryu is right; I need to be able to 'offset' the string so that I can return any subdivision of it, regardless of where the string starts or ends (so a subdivision of length 5 _could_ consist of '78912', for example. – Luka Manitta Mar 03 '20 at 03:52

4 Answers4

3
myString = '123456789'
s = myString[1:-1]

You were close. It's 1:-1.

If you are looking for the output 91:

s = myString[-1] + s = myString[0]
# 91
Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
  • "slice" is not a keyword. If it were a keyword, it would not be possible to use it as a variable name. – khelwood Mar 02 '20 at 23:26
0

If you want a to represent the string as a circular array, and if you want to slice parts OUT of the string, you will want to convert it to something else first, as Python strings are immutable. Collections.deque is going to be a bit more efficient than a list:

from collections import deque
foo = deque('123456789')
result = str(foo.pop() + foo.popleft()  # result then is == '91' and 
                                        # str(''.join(foo)) == '2345678'

If you just want to cycle over the array looking for a substring (i.e. holding the position steady while spinning the array, if that's what you mean) you can do something like this without altering the array:

foo = deque('123456789')
for x in range(len(foo)):   #have to use range here (mutation during iteration)
    print(str(''.join(foo[-1] + foo[0])))  
    foo.rotate(1)     

This results in 91 89 78 67 56 45 23 12

neutrino_logic
  • 1,289
  • 1
  • 6
  • 11
0
myString = '123456789'

def mySlice(mstring, start, end):
    if (start<0 or start>end):
        new_str=mstring[start:len(mstring)]+mstring[0:end]
    else:
        old_str=mstring[start:end]
        return old_str
    return new_str

slice = mySlice(myString, -1, 1)
print(slice) #output is 91
Gryu
  • 2,102
  • 2
  • 16
  • 29
0

slice a first and last characteres by using slice and take variables a and b after that concate two variables

myString = '123456789'
a = myString[-1]
b = myString[0]
print(a + b)

result

91
vijju
  • 21
  • 2