0

Please consider below code, I want to reversed the first two elements. That is target string is "abcd", the first two elements is "ab", and i need "ba". How can i use below code to do it? (I know i have alternative ways to do, but how to do in below way?)

    r = "abcd"
    t = r[1:0:-1]
    print(t)
    # print b

Another way:

    r = "abcd"
    t = r[1:-1:-1]
    print(t)
    # print NOTHING!
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
DingLi
  • 791
  • 10
  • 19
  • `’abcd’[1::-1]` – jonrsharpe Sep 29 '17 at 06:52
  • @jonrsharpe the top answer in that question actually does not explain what happens when you include `start` and `step`, but leave `stop` blank. The third top answer even gives the *wrong* information (when `step` is negative, as it is here). Is this really a duplicate? – Jeremy McGibbon Sep 29 '17 at 07:00
  • @JeremyMcGibbon then by all means suggest improvements, but we don’t need a separate new question for every possible use of slicing, that’s why the canonical dupes exist. – jonrsharpe Sep 29 '17 at 07:02

1 Answers1

3

You're close! You need to remove the 0 from your indexing expression. Your indexing expression is of the form start:stop:step, where stop is not included. If you don't put any value for stop, then it will continue until the end of the string (in this case, the start of the string, since step is negative).

r = "abcd"
t = r[1::-1]
print(t)  # prints 'ba'
Jeremy McGibbon
  • 3,527
  • 14
  • 22
  • O thank you. That's working, but considering below case: for a string 'abcdefghijk', for every 4 chars, i need to reversed the first two. How can I do this by without explicit check it is the first char and i should put empty in stop? – DingLi Sep 29 '17 at 07:02
  • I have add sample code in question, thank you! – DingLi Sep 29 '17 at 07:04
  • @DingLi do not change questions after receiving answers. Ask the thing you actually want to know to start with. – jonrsharpe Sep 29 '17 at 07:14