Talk briefly about reversing strings in Python

  • 2020-05-12 02:52:41
  • OfStack

Reversing a string by word is a very common interview question. It's very simple 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 Power

s = 'Hello World!'
print reverse_string_by_word(s)
# World! Hello

The above implementation works in most cases, but it's 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 preserved. (in the above example there is actually more than one space between Hello and World.)

That's what we're looking for.


print reverse_string_by_word(s)
# Expected: !World Hello

To improve the above scheme without complicating matters, it is recommended to use the re module. You can refer to the official documentation for re.split (). Let's look at a concrete 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 don't think slicing backwards is very readable, you can write it this way.


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

In one sentence, so easy!

Python flipped string (reverse string), 1 contains 5 methods in total, among which the first method is the simplest, namely the step size is -1, output string;

Methods the following

Comparison of 5 methods:

1. The simple step size is -1, that is, the inversion of the string (commonly used);
2. Exchange the positions of letters before and after;
3. Recursively output 1 character at a time;
4. Double-end queue, using extendleft() function;
5. Output from left to right using for loop;

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 


Related articles: