只需一行代码,实现字符串的反转。简洁明了。

参考stackflow上的答案

示例:

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

s = "hello world!"
s = reverse(s)

print (s)

运行结果:

!dlrow olleh

原理:

原文:This is extended slice syntax. It works by doing [begin : end : step] - by leaving begin and end off and specifying a step of -1, it reverses a string.

个人理解就是三个参数:

  • begin代表起始位置
  • end指示了终止位置
  • step就是步长,即指示下一个字符的位置。
Last modification:April 19th, 2019 at 06:28 pm
If you think my article is useful to you, please feel free to appreciate