Python中采用不同的方法将字符串倒序输出

Python中采用不同的方法将字符串倒序输出

逆转字符串的方法有好多种,在这里我只介绍两种简单的方法

1.采用切片

str = "This is a test of python"
new_str = str[::-1]
print(new_str)

2.利用列表进行反转

str = "This is a test of python"
reverse = []
for i in str:   #遍历字符串
    reverse.append(i)   #将字符串每个元素添加到列表中
reverse.reverse()   #反转列表
new_str = "".join(reverse)  #将列表转为字符串
print(new_str)

输出结果:

nohtyp fo tset a si sihT
nohtyp fo tset a si sihT

你可能感兴趣的:(Python中采用不同的方法将字符串倒序输出)