user3926579
user3926579

Reputation: 67

Reversing a slice of a Python string

I am trying to get this string to read backwards, however I am having trouble shifting it to start iterating back from h instead of g without changing the variables text, start and end?

text = 'abcdefghij'
start = 1
end = 7
back = text [start:end] [::-1]
print back

The result I get is gfedcb but what I want is hgfedc.

Upvotes: 2

Views: 85

Answers (2)

Jason S
Jason S

Reputation: 13779

There is no need to slice twice.

>>> text[end:start:-1]
'hgfedc'

As a bonus, switching the order of start and end also switches the open/closed end of the range so you don't have to add or subtract 1 in this case.

Upvotes: 3

the
the

Reputation: 21891

What about this?

>>> print text[start+1:end+1][::-1]
hgfedc

Upvotes: 1

Related Questions