python3反转字符串的3种方法(小结)

yipeiwu_com6年前Python基础

前段时间看到letcode上的元音字母字符串反转的题目,今天来研究一下字符串反转的内容。主要有三种方法:

1.切片法(最简洁的一种)

#切片法
def reverse1():
  s=input("请输入需要反转的内容:")
  return s[::-1]
reverse1()

#运行结果
In [23]: def reverse1():
  ...: s=input("请输入需要反转的内容:")
  ...: return s[::-1]
  ...: 
  ...: reverse1()

请输入需要反转的内容:你是一个小南瓜
Out[23]: '瓜南小个一是你'

原理是: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.

2.递归

#递归反转
def reverse2(s):
  if s=="":
    return s
  else:
    return reverse2(s[1:])+s[0]
reverse2("sidfmawsmdisd是当面问")

#运行结果
In [24]: def reverse2(s):
  ...: if s=="":
  ...: return s
  ...: else:
  ...: return reverse2(s[1:])+s[0]
  ...: 
  ...: reverse2("sidfmawsmdisd是当面问")
Out[24]: '问面当是dsidmswamfdis'

3.借用列表,使用reverse()方法

Python中自带reverse()函数,可以处理列表的反转,来看示例:

In [25]: l=['a', 'b', 'c', 'd']
  ...: l.reverse()
  ...: print (l)
['d', 'c', 'b', 'a']

reverse()函数将列表的内容进行了反转,借助这个特性,可以先将字符串转换成列表,利用reverse()函数进行反转后,再处理成字符串。

#借用列表,使用reverse()方法
def reverse3(s):
  l=list(s)
  l.reverse()
  print("".join(l))
reverse3("soifmi34pomOsprey,,是")

#运行结果
In [26]: def reverse3(s):
  ...: l=list(s)
  ...: l.reverse()
  ...: print("".join(l))
  ...: 
  ...: reverse3("soifmi34pomOsprey,,是")
  ...: 

是,,yerpsOmop43imfios

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3.3教程之模拟百度登陆代码分享

复制代码 代码如下:#-*-coding:utf-8-*-'''Created on 2014年1月10日 @author: hhdys'''import urllib.request,...

tensorflow之获取tensor的shape作为max_pool的ksize实例

实验发现,tensorflow的tensor张量的shape不支持直接作为tf.max_pool的参数,比如下面这种情况(一个错误的示范): self.max_pooling1 =...

python检测空间储存剩余大小和指定文件夹内存占用的实例

1、检测指定路径下所有文件所占用内存 import os def check_memory(path, style='M'): i = 0 for dirpath, dirnam...

在Python中使用第三方模块的教程

在Python中,安装第三方模块,是通过setuptools这个工具完成的。Python有两个封装了setuptools的包管理工具:easy_install和pip。目前官方推荐使用p...

详解python中docx库的安装过程

详解python中docx库的安装过程

python中docx库的简介 python-docx包,这是一个很强大的包,可以用来创建docx文档,包含段落、分页符、表格、图片、标题、样式等几乎所有的word文档中能常用的功能都包...