python3 反转字符串的两种方式

code

def reverse_str(tmp):
    alist=list(tmp)
    startIndex = 0
    endIndex = len(alist) - 1
    while startIndex < endIndex:
        alist[startIndex], alist[endIndex] = alist[endIndex], alist[startIndex]
        startIndex += 1
        endIndex -= 1
    return "".join(alist)

def reverse_str2(tmp):
    return tmp[::-1]


tmp="abcdefg"
print(reverse_str(tmp))
print(reverse_str2(tmp))

outputs

macname@MacdeMBP ~ % python3 test.py
gfedcba
gfedcba
macname@MacdeMBP ~ % 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-10-04 11:21  anobscureretreat  阅读(273)  评论(0编辑  收藏  举报