-1

I have a alphabet string like:

string = 'abcdefghijklmnopqrstuvwxyz'

if want to do slicing and and go from z to a but with 3 steps. what should I do? I know string[::-1] will reverse it but how can I make it go by 3 steps each time?

I have done it by assigning a new string which is reverse of the other string and do slicing with 3 steps from there. I'm looking for a new way to do it without changing the previous string and doing it on the same spot

pault
  • 41,343
  • 15
  • 107
  • 149
Ali A.
  • 27
  • 1
  • 3
    Possible duplicate of [Understanding slice notation](https://stackoverflow.com/questions/509211/understanding-slice-notation) – pault May 22 '19 at 19:47
  • What's the desired output? Also, strings are immutaable so you can't modify it in place. – pault May 22 '19 at 19:48
  • 3
    Surely `string[::-3] ` is a natural try -- did you *try* it? The Python shell allows for quick experimentation, which can give you an answer much more quickly than Stack Overflow. – John Coleman May 22 '19 at 19:53

2 Answers2

1

The last number in the slice is the interval:

string = 'abcdefghijklmnopqrstuvwxyz'
string[::-3]
'zwtqnkheb'
d_kennetz
  • 5,219
  • 5
  • 21
  • 44
0

If you want 3 letter slices starting from the end and going backward, you can use a list comprehension:

string = 'abcdefghijklmnopqrstuvwxyz'
slices =  [ string[i:i+3][::-1] for i in range(len(string)-3,0,-3) ]

# ['zyx', 'wvu', 'tsr', 'qpo', 'nml', 'kji', 'hgf', 'edc']
Alain T.
  • 40,517
  • 4
  • 31
  • 51