python 实现字符串反转

方式一:字符串切片

first_str = "123456"
# 字符串反向截取
new_str = first_str[::-1]
print("first_str: ", first_str)
print("new_str:   ", new_str)


方式二:list反转

# list 反转
first_str = "123456"
list_str = list(first_str)
list_str.reverse()
new_str2 = "".join(list_str)
print("first_str: ", first_str)
print("new_str:   ", new_str2)

方式三:reduce();reduce()函数会对参数序列中元素进行累积;

from functools import reduce 
first_str = "123456" 
new_str3 = reduce(lambda x,y:y+x,first_str)
print("first_str: ", first_str)
print("new_str3:  ", new_str3)






猜你喜欢

转载自blog.csdn.net/wjunsing/article/details/79862521