Python的str对象没有内置的反向函数。实施此方法的最佳方式是什么?

如果提供一个非常简洁的答案,请详细说明其效率。例如,str对象是否转换为其他对象等。


当前回答

1.使用切片表示法

def rev_string(s): 
    return s[::-1]

2.使用reversed()函数

def rev_string(s): 
    return ''.join(reversed(s))

3.使用递归

def rev_string(s): 
    if len(s) == 1:
        return s

    return s[-1] + rev_string(s[:-1])

其他回答

递归方法:

def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])

例子:

print(reverse("Hello!"))    #!olleH
original = "string"

rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw

print(original)
print(rev_index)
print(''.join(rev_func))

以编程方式解决面试问题

def reverse_a_string(string: str) -> str:
    """
    This method is used to reverse a string.
    Args:
        string: a string to reverse

    Returns: a reversed string
    """
    if type(string) != str:
        raise TypeError("{0} This not a string, Please provide a string!".format(type(string)))
    string_place_holder = ""
    start = 0
    end = len(string) - 1
    if end >= 1:
        while start <= end:
            string_place_holder = string_place_holder + string[end]
            end -= 1
        return string_place_holder
    else:
        return string


a = "hello world"
rev = reverse_a_string(a)
print(rev)

输出:

dlrow olleh

一个不那么令人困惑的方法是:

string = 'happy'
print(string)

“快乐”

string_reversed = string[-1::-1]
print(string_reversed)

'伊帕'

英语[-1::-1]如下:

“从-1开始,一直走,采取-1的步骤”

def reverse_string(string):
    length = len(string)
    temp = ''
    for i in range(length):
        temp += string[length - i - 1]
    return temp

print(reverse_string('foo')) #prints "oof"

这通过循环一个字符串并将其值按相反顺序分配给另一个字符串来实现。