Python字符串逆序输出的实例讲解
作者:世界看我我看世界 时间:2023-04-21 22:59:46
1、有时候我们可能想让字符串倒序输出,下面给出几种方法
方法一:通过索引的方法
>>> strA = "abcdegfgijlk"
>>> strA[::-1]
'kljigfgedcba'
方法二:借组列表进行翻转
#coding=utf-8
strA = raw_input("请输入需要翻转的字符串:")
order = []
for i in strA:
order.append(i)
order.reverse() #将列表反转
print ''.join(order) #将list转换成字符串
执行结果:
请输入需要翻转的字符串:abcdeggsdd
ddsggedcba
2、分别输出字符串中奇数坐标和偶数坐标的字符
最简单的方法是根据序列的切片来实现。
>>> str_a = "1a2b3c4d5e6f"
***输出奇数位的字符***
>>> for i in str_a[::2]:
... print i,
...
1 2 3 4 5 6
***输出偶数位的字符***
>>> for j in str_a[1::2]:
... print j,
...
a b c d e f
当然我们也可以使用下面的方法实现,但是这种方法就比较麻烦了。
#coding=utf-8
def oddEven(strA):
odd = []
even = []
for i in range(len(strA)):
if i % 2 == 0:
even.append(strA[i])
else :
odd.append(strA[i])
print "偶数项:", ''.join(even)
print "奇数项:", ''.join(odd)
strA = "1a2b3c4d5e6f7g8h9j"
print "原字符串:", strA
oddEven(strA)
执行结果:
原字符串: 1a2b3c4d5e6f7g8h9j
偶数项: 123456789
奇数项: abcdefghj
值得注意的是:
在我们平常的编程过程中,一定要避免直接使用编程语言的关键字作为变量名,尤其是Python语言中几乎所有的对象都可以赋值,如果将系统环境给的变量赋值经常会造成很多奇怪的问题,所以一定要养成好的编程习惯。
最典型一个就是关于isinstance()函数的报错,代码写的是没有问题,但是就是会报错,说明在这代码之前str肯定被当着变量赋过值。
>>> a = '123'
>>> isinstance(a, str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
来源:https://blog.csdn.net/seetheworld518/article/details/46756639
标签:python,字符串,逆序输出
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python类型转换的魔术方法详解
2022-04-16 12:49:06
python字典快速保存于读取的方法
2022-02-18 02:22:11
python isinstance函数用法详解
2023-05-08 12:43:56
使用Python的Tornado框架实现一个Web端图书展示页面
2022-04-23 07:23:48
![](https://img.aspxhome.com/file/2023/2/109332_0s.png)
PHP.vs.JAVA
2023-11-17 20:28:51
![](https://img.aspxhome.com/file/2023/2/85872_0s.jpg)
网站发布后Bootstrap框架引用woff字体无法正常显示的解决方法
2023-08-13 00:26:58
python中asyncio异步编程学习
2022-10-20 06:19:37
JS如何获取变量值
2008-05-18 12:52:00
用Python进行TCP网络编程的教程
2021-07-31 06:06:07
![](https://img.aspxhome.com/file/2023/3/89453_0s.png)
多级联动下拉选择框,动态获取下一级
2008-09-04 10:34:00
Python图像分割之均匀性度量法分析
2021-02-11 11:45:24
![](https://img.aspxhome.com/file/2023/2/72872_0s.png)
python访问sqlserver示例
2022-07-15 07:25:01
Python pandas处理缺失值方法详解(dropna、drop、fillna)
2023-04-03 03:45:36
python使用正则表达式提取网页URL的方法
2023-10-09 16:27:18
python 利用jieba.analyse进行 关键词提取
2021-03-16 22:11:26
![](https://img.aspxhome.com/file/2023/5/78575_0s.png)
Python调用高德API实现批量地址转经纬度并写入表格的功能
2023-12-26 03:22:20
![](https://img.aspxhome.com/file/2023/3/101673_0s.png)
浅谈Python peewee 使用经验
2023-09-14 14:20:55
Python查找多个字典公共键key的方法
2022-12-01 09:53:58
处理HTML代码的若干函数
2009-08-21 13:21:00
Python图形绘制操作之正弦曲线实现方法分析
2023-07-05 11:18:59
![](https://img.aspxhome.com/file/2023/3/60513_0s.png)