1,105,371 Community Members

Python string reversed explanation

Member Avatar
nunos
Light Poster
46 posts since Aug 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I was googling for a way to reverse a string and I found this.

>>> 'asd'[::-1]
>>> 'dsa'

It works, but there was no explanation where I got if from. Can someone please be kind enough to explain it. Thanks.

Member Avatar
sneekula
Nearly a Posting Maven
2,496 posts since Oct 2006
Reputation Points: 917 [?]
Q&As Helped to Solve: 263 [?]
Skill Endorsements: 5 [?]
 
1
 

You have to read up on the slicing operator in the Python Manual.

Generally you can slice a sequence with [start: end: step]
By default start=0, end=len(seq), step=1
step=-1 goes from the end to the beginning of the sequence, hence your reverse.

For some nice slicing examples see post #4 at;
http://www.daniweb.com/forums/post104865.html#post104865

Member Avatar
Friktion
Newbie Poster
15 posts since Jun 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 0 [?]
 
0
 

wow ^^ even i didn't know that

Member Avatar
nunos
Light Poster
46 posts since Aug 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

You have to read up on the slicing operator in the Python Manual.

Generally you can slice a sequence with [start: end: step]
By default start=0, end=len(seq), step=1
step=-1 goes from the end to the beginning of the sequence, hence your reverse.

For some nice slicing examples see post #4 at;
http://www.daniweb.com/forums/post104865.html#post104865

I have used slice notation in the past. I wasn't aware that there was the 'step'. Thanks for your reply and link to the post.

Question Answered as of 4 Years Ago by sneekula and Friktion
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: