Python反转字符串

时间:2020-02-23 14:43:15  来源:igfitidea点击:

Python String没有内置的reverse()函数。
但是,有多种方法可以在Python中反转字符串。

1.如何在Python中反转字符串?

反转字符串的一些常见方法是:

  • 使用切片来创建字符串的反向副本。
  • 使用for循环并以相反顺序附加字符
  • 使用while循环以相反的顺序迭代字符串字符并附加它们
  • 在反向()迭代器中使用字符串join()函数
  • 从字符串创建列表,然后调用其reverse()函数
  • 使用递归

1.1)使用切片的Python反向字符串

def reverse_slicing(s):
  return s[::-1]

input_str = 'ABç∂EF'

if __name__ == "__main__":
  print('Reverse String using slicing =', reverse_slicing(input_str))

如果您在Python脚本上运行,则输出为:

Reverse String using slicing = FE∂çBA

1.2)使用For循环反向字符串

def reverse_for_loop(s):
  s1 = ''
  for c in s:
      s1 = c + s1  # appending chars in reverse order
  return s1

input_str = 'ABç∂EF'

if __name__ == "__main__":
  print('Reverse String using for loop =', reverse_for_loop(input_str))

1.3)使用While循环反转字符串

def reverse_while_loop(s):
  s1 = ''
  length = len(s) - 1
  while length >= 0:
      s1 = s1 + s[length]
      length = length - 1
  return s1

input_str = 'ABç∂EF'

if __name__ == "__main__":
  print('Reverse String using while loop =', reverse_while_loop(input_str))

1.4)使用join()和reversed()反转字符串

def reverse_join_reversed_iter(s):
  s1 = ''.join(reversed(s))
  return s1

1.5)使用列表reverse()的Python反向字符串

def reverse_list(s):
  temp_list = list(s)
  temp_list.reverse()
  return ''.join(temp_list)

1.6)使用递归的Python反向字符串

def reverse_recursion(s):
  if len(s) == 0:
      return s
  else:
      return reverse_recursion(s[1:]) + s[0]

2.用Python反转字符串的最佳方法

我们可以通过多种算法反转字符串。
我们已经看过其中的六个。
但是您应该选择其中的哪一个反向字符串。

我们可以使用timeit模块来运行这些函数的多次迭代,并获得运行它们所需的平均时间。

以上所有功能均存储在名为string_reverse.py的python脚本中。
我使用timeit模块逐个执行了所有这些功能1,00,000次,并得到了5次最佳运行的平均值。

$python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_slicing("ABç∂EF"*10)'
100000 loops, best of 5: 0.449 usec per loop

$python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_list("ABç∂EF"*10)'
100000 loops, best of 5: 2.46 usec per loop

$python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_join_reversed_iter("ABç∂EF"*10)'
100000 loops, best of 5: 2.49 usec per loop

$python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_for_loop("ABç∂EF"*10)'
100000 loops, best of 5: 5.5 usec per loop

$python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_while_loop("ABç∂EF"*10)'
100000 loops, best of 5: 9.4 usec per loop

$python3.7 -m timeit --number 100000 --unit usec 'import string_reverse' 'string_reverse.reverse_recursion("ABç∂EF"*10)'
100000 loops, best of 5: 24.3 usec per loop

下表列出了最佳算法的结果和慢度。

AlgorithmTimeIt Execution Time (Best of 5)Slowness
Slicing0.449 usec1x
List reverse()2.46 usec5.48x
reversed() + join()2.49 usec5.55x
for loop5.5 usec12.25x
while loop9.4 usec20.94x
Recursion24.3 usec54.12x