python字符串反向输出

Python String doesn’t have a built-in reverse() function. However, there are various ways to reverse a string in Python.

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

1.如何在Python中反转字符串? (1. How to Reverse a String in Python?)

Some of the common ways to reverse a string are:

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

  • Using Slicing to create a reverse copy of the string.使用切片来创建字符串的反向副本。
  • Using for loop and appending characters in reverse order使用for循环并以相反顺序附加字符
  • Using while loop to iterate string characters in reverse order and append them使用while循环以相反的顺序迭代字符串字符并追加它们
  • Using string join() function with reversed() iterator在反向()迭代器中使用字符串join()函数
  • Creating a list from the string and then calling its reverse() function从字符串创建列表 ,然后调用其reverse()函数
  • Using Recursion使用递归

1.1)使用切片的Python反向字符串 (1.1) Python Reverse String using Slicing)

def reverse_slicing(s):return s[::-1]input_str = 'ABç∂EF'if __name__ == "__main__":print('Reverse String using slicing =', reverse_slicing(input_str))

If you run above Python script, the output will be:

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

Reverse String using slicing = FE∂çBA

1.2)使用For循环反向字符串 (1.2) Reverse String using For Loop)

def reverse_for_loop(s):s1 = ''for c in s:s1 = c + s1  # appending chars in reverse orderreturn s1input_str = 'ABç∂EF'if __name__ == "__main__":print('Reverse String using for loop =', reverse_for_loop(input_str))

Output: Reverse String using for loop = FE∂çBA

输出: Reverse String using for loop = FE∂çBA

1.3)使用While循环反转字符串 (1.3) Reverse a String using While Loop)

def reverse_while_loop(s):s1 = ''length = len(s) - 1while length >= 0:s1 = s1 + s[length]length = length - 1return s1input_str = 'ABç∂EF'if __name__ == "__main__":print('Reverse String using while loop =', reverse_while_loop(input_str))

1.4)使用join()和reversed()反转字符串 (1.4) Reverse a String using join() and reversed())

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

1.5)使用列表reverse()的Python反向字符串 (1.5) Python Reverse String using List reverse())

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

1.6)使用递归的Python反向字符串 (1.6) Python Reverse String using Recursion)

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

2.用Python反转字符串的最佳方法 (2. Best Way to Reverse a String in Python)

We can reverse a string through multiple algorithms. We have already seen six of them. But which of them you should choose to reverse a string.

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

We can use timeit module to run multiple iterations of these functions and get the average time required to run them.

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

All the above functions are stored in a python script named string_reverse.py. I executed all these functions one by one for 1,00,000 times using the timeit module and got the average of the best 5 runs.

以上所有功能均存储在名为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

The below table presents the results and slowness of an algorithm from the best one.

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

.tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-md4w{background-color:#D2E4FC;text-align:left} .tg .tg-s268{text-align:left}.tg {border-collapse:collapse;border-spacing:0;border-color:#999;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#444;background-color:#F7FDFA;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:#999;color:#fff;background-color:#26ADE4;} .tg .tg-md4w{background-color:#D2E4FC;text-align:left} .tg .tg-s268{text-align:left}

Algorithm TimeIt Execution Time (Best of 5) Slowness
Slicing 0.449 usec 1x
List reverse() 2.46 usec 5.48x
reversed() + join() 2.49 usec 5.55x
for loop 5.5 usec 12.25x
while loop 9.4 usec 20.94x
Recursion 24.3 usec 54.12x
算法 TimeIt执行时间(最佳5) 缓慢
切片 0.449微秒 1倍
列出reverse() 2.46微秒 5.48倍
reversed()+ join() 2.49微秒 5.55倍
for循环 5.5微秒 12.25倍
while循环 9.4用 20.94倍
递归 24.3微秒 54.12倍

3.总结 (3. Summary)

We should use slicing to reverse a string in Python. Its code is very simple and small and we don’t need to write our own logic to reverse the string. Also, it’s the fastest way to reverse a string as identified by the above test executions.

我们应该使用切片来反转Python中的字符串。 它的代码非常简单小巧,我们不需要编写自己的逻辑来反转字符串。 另外,这是反转上述测试执行所确定的字符串的最快方法。

GitHub Repository.GitHub存储库中检出完整的python脚本和更多Python示例。

4.参考 (4. References)

  • reversed() API Docreversed()API文档
  • str.join() API Docstr.join()API文档

翻译自: https://www.journaldev.com/23647/python-reverse-string

python字符串反向输出

python字符串反向输出_Python反向字符串– 5种方法和最佳方法相关推荐

  1. python 字符串遍历输出_python遍历字符串的方法有哪些

    python遍历字符串的方法有哪些 发布时间:2020-08-11 09:19:54 来源:亿速云 阅读:103 作者:小新 这篇文章将为大家详细讲解有关python遍历字符串的方法有哪些,小编觉得挺 ...

  2. python3 练习题100例 (二十二)输入两个字符串,输出两个字符串集合的并集

    题目内容: 输入两个字符串,输出两个字符串集合的并集. 为保证输出结果一致,请将集合内元素排序之后再输出, 如对于集合aset,可输出sorted(aset). 输入格式: 共两行,每一行为一个字符串 ...

  3. C语言:从键盘输入两个字符串,输出第一个字符串在第二个字符串中的位置

    从键盘输入两个字符串,输出第一个字符串的首字母在第二个字符串中的位置. 如"abc"在"bbbacccabcddaw3"的位置为7. 悬赏分:50 | 解决时间 ...

  4. python语言格式化输出_Python | 格式化输出字符串

    一直以来,字符串的格式化输出对于编程来说,尤其是新手,还是挺麻烦的.对于这部分的内容,笔者的建议是,只要大致能满足输出要求,越简单越好,别整那复杂的~(图文无关[俏皮]) 工具/原料 Python 2 ...

  5. python语言格式化输出_Python字符串格式化输出

    原博文 2019-11-22 12:48 − 本文链接:https://www.cnblogs.com/zyuanlbj/p/11910913.html 使用占位符%s name = '小飞' pri ...

  6. python字符数组输出_python字符串格式化输出

    字符串格式化输出 : 字符串的拼接第一种方式 如:name = input("name:") age = input("age:") job = input(& ...

  7. python列表换行输出_Python从列表转换为字符串时处理换行符

    我有一个关于换行符和返回字符的问题.呃,这很难解释,但我会尽力的. 我有列表形式的数据.列表的成员中有换行符,因此. 1 2 3example_list = ["I've always lo ...

  8. python shell怎么运行字符串拼接无输出_Python拼接字符串的7种方法总结

    前言 忘了在哪看到一位编程大牛调侃,他说程序员每天就做两件事,其中之一就是处理字符串.相信不少同学会有同感. 在Python中,我们经常会遇到字符串的拼接问题,几乎任何一种编程语言,都把字符串列为最基 ...

  9. python字符串逆序_python之字符串逆序

    python之字符串逆序 1.贴题 题目来自PythonTip 给你一个字符串 a, 请你输出逆序之后的a. 例如:a='xydz' 则输出:zdyx 2.说明 思路基本分为两种, 一是编写循环,每次 ...

最新文章

  1. pyqt4+chatterbot实现简单聊天机器人程序
  2. MYSQL管理之主从同步管理
  3. 光用滴答清单也可以专注学习
  4. 【Java HashMap】常用函数的使用
  5. 看动画学算法之:队列queue
  6. [ lucene FAQ ] 当磁盘索引被IndexSearcher打开时,为什么优化操作后索引容量翻倍?...
  7. Razor与HTML混合输出陷阱与技巧
  8. VS2005为什么会自动关闭?使用Visual Assist X的要注意了
  9. 自拍就可以得到你自己的个人贴图 Gboard打造客制化贴图
  10. 解析OA技术,规避使用风险
  11. 服务应用监控健康检测
  12. 英伟达推出新款“煤气灶”Titan RTX,售价近2万,并开源PhysX SDK
  13. PostgreSQL学习手册(十一) 数据库管理
  14. asset文件夹路径 unity_Unity3D研究院之手游开发中所有特殊的文件夹
  15. Ripro子主题Eeesucai-child集成后台美化包源码
  16. 充电速度公式_锂电充电时间计算公式
  17. JS 的内联模式与外联模式
  18. 英文字母或者中文字母文本替换
  19. 实习第五天 工作总结
  20. 基于Android平台的小说阅读APP的设计与实现

热门文章

  1. 非常简单,让log4j输出mybatis的sql语句和执行结果
  2. Hacker News的全文输出RSS地址
  3. javascript数字补零
  4. [转载] 了解Node.js-to-Angular 套件组件
  5. verilog之用户定义原语UDP详细解释
  6. Java匹马行天下之C国程序员的秃头原因
  7. 字符转获取拼音首字母php实现
  8. 【Go】优雅的读取http请求或响应的数据-续
  9. Servlet/JSP-02 Servlet相关类
  10. 《深入理解Spark:核心思想与源码分析》——SparkContext的初始化(叔篇)——TaskScheduler的启动...