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 ~ % 

原文地址:https://www.cnblogs.com/sea-stream/p/13766765.html