How to reverse a string achieve? Python achieve

  Today, a colleague and went out for dinner, then a sudden wind change, Khao ask me a question, he said, brother, you know how to reverse a string? I thought, I rub, go home to see my blog as a senior development , how could be a feather boy asked to live!

So I tried a little bit of finishing today, on the issue came, hoping to help you!

  Python string is one of the most the most common type of data

      For example, given you string = 'abcdefg'

      Cold look ask you this question, and you may ask to live!

      Here are a few ways I am finishing, easy to understand, beginners can understand!

  

The first method: Slice implement simple and practical recommended 

1 string='abcdefg'
2 print(string[::-1])
View Code

 

The second method uses reduce looked taller on slow

1 reduce(lambda x,y : y+x, a_string)
View Code

 

The third method uses the list loop stitching slow

1 string='abcdefg'
2 lst=[]
3 lst.extend(string)
4 lst.reverse()
5 new_string = ''
6 for st in lst:
7     new_string = new_string + st
8 print(new_string)
View Code

 

Fourth, according to the length, to give a final index value, the index value according to the cycle from the rear, do not write code demonstrates

 

You can also use the stack implementation, only the first of these methods is the fastest and easiest, collection of it! Finishing easy!

Guess you like

Origin www.cnblogs.com/well-666/p/11221926.html