在实际的工作中,常会对字符串或者列表等序列数据对象进行反转操作,那如何实现了,快来看看吧!直接上代码如下
#
# 字符串反转
#
str1 = '''Python is a awesome language, learning with BYHY'''
print(str1)
# 方法1:切片
print(str1[::-1])
# 方法2:遍历打印
for char in reversed(str1):
print(char)
# 方法3:对非字符串类型对象,强制类型转换为str类型
num1 = 123456789
print(num1)
print(int(str(num1)[::-1]))
输出结果如下:
Python is a awesome language, learning with BYHY
YHYB htiw gninrael ,egaugnal emosewa a si nohtyP
p
i
v
.
3
.....
123456789
987654321
#
# 列表反转
#
# 方法1:切片
list1 = [1, 2, 3, 4, 5]
print(list1[::-1])
# 方法2:遍历+reversed 方法
for ele in reversed(list1):
print(ele)
输出结果:
[5, 4, 3, 2, 1]
5
4
3
2
1
了解更多,请参考白月黑羽在线教程
#
# 字符串反转
#
str1 = '''Python is a awesome language, learning with BYHY'''
print(str1)
# 方法1:切片
print(str1[::-1])
# 方法2:遍历打印
for char in reversed(str1):
print(char)
# 方法3:对非字符串类型对象,强制类型转换为str类型
num1 = 123456789
print(num1)
print(int(str(num1)[::-1]))
输出结果如下:
Python is a awesome language, learning with BYHY
YHYB htiw gninrael ,egaugnal emosewa a si nohtyP
p
i
v
.
3
.....
123456789
987654321
#
# 列表反转
#
# 方法1:切片
list1 = [1, 2, 3, 4, 5]
print(list1[::-1])
# 方法2:遍历+reversed 方法
for ele in reversed(list1):
print(ele)
输出结果:
[5, 4, 3, 2, 1]
5
4
3
2
1
了解更多,请参考白月黑羽在线教程