Let's talk about reverse string in Python.

Source: Internet
Author: User

Let's talk about reverse string in Python.

Reversing strings by word is a common interview question. It is very easy to implement in Python.

def reverse_string_by_word(s): lst = s.split() # split by blank space by default return ' '.join(lst[::-1])s = 'Power of Love'print reverse_string_by_word(s)# Love of Powers = 'Hello World!'print reverse_string_by_word(s)# World! Hello

The above implementation can satisfy most situations, but it is not perfect. For example, the exclamation point in the second string is not flipped and the number of spaces in the original string is not retained. (In the above example, there is actually more than one space between Hello and World)

The expected result is like this.

print reverse_string_by_word(s)# Expected: !World Hello

To improve the above solution, we do not complicate the problem. We recommend that you use the re module. You can refer to the official documents of re. split. Let's take a look at the specific example.

>>> import re>>> s = 'Hello World!'>>> re.split(r'\s+', s) # will discard blank spaces['Hello', 'World!']>>> re.split(r'(\s+)', s) # will keep spaces as a group['Hello', ' ', 'World!']>>> s = '< Welcome to EF.COM! >'>>> re.split(r'\s+', s) # split by spaces['<', 'Welcome', 'to', 'EF.COM!', '>']>>> re.split(r'(\w+)', s) # exactly split by word['< ', 'Welcome', ' ', 'to', ' ', 'EF', '.', 'COM', '! >']>>> re.split(r'(\s+|\w+)', s) # split by space and word['<', ' ', '', 'Welcome', '', ' ', '', 'to', '', ' ', '', 'EF', '.', 'COM', '!', ' ', '>']>>> ''.join(re.split(r'(\s+|\w+)', s)[::-1])'> !COM.EF to Welcome <'>>> ''.join(re.split(r'(\s+)', s)[::-1])'> EF.COM! to Welcome <'>>> ''.join(re.split(r'(\w+)', s)[::-1])'! >COM.EF to Welcome< '

If you think that the reverse sequence is not highly readable by using slice, you can also write it like this.

>>> ''.join(reversed(re.split(r'(\s+|\w+)', s)))'> !COM.EF to Welcome <'

So easy!

Python flip string (reverse string ),There are five methods in total. The first method is the simplest, that is, the step size is-1, and the output string;

The method is as follows:

Comparison of the five methods:

1. The simple step is-1, that is, string flip (commonly used );
2. Change the positions of the front and back letters;
3. recursively output one character each time;
4. Double-end queue, using the extendleft () function;
5. Use the for loop to output data from left to right;

Code:

# -*- coding: utf-8 -*-  #eclipse pydev, python 3.3 #by C.L.Wang #time: 2014. 4. 11  string = 'abcdef'  def string_reverse1(string):  return string[::-1]  def string_reverse2(string):  t = list(string)  l = len(t)  for i,j in zip(range(l-1, 0, -1), range(l//2)):   t[i], t[j] = t[j], t[i]  return "".join(t)  def string_reverse3(string):  if len(string) <= 1:   return string  return string_reverse3(string[1:]) + string[0]  from collections import deque def string_reverse4(string):  d = deque()  d.extendleft(string)  return ''.join(d)  def string_reverse5(string):  #return ''.join(string[len(string) - i] for i in range(1, len(string)+1))  return ''.join(string[i] for i in range(len(string)-1, -1, -1))  print(string_reverse1(string)) print(string_reverse2(string)) print(string_reverse3(string)) print(string_reverse4(string)) print(string_reverse5(string)) 

Output:

fedcba fedcba fedcba fedcba fedcba 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.