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

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


当前回答

作为一种不同的解决方案(因为面试中会问到):

def reverse_checker(string):
    ns = ""
    for h in range(1,len(string)+1):
        ns  += string[-h]
    print(ns)

    if ns == string:
        return True
    else:
        return False

其他回答

original = "string"

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

print(original)
print(rev_index)
print(''.join(rev_func))
 a=input()
 print(a[::-1])

上述代码接收来自用户的输入,并通过添加[::-1]打印与输入相反的输出。

输出:

>>> Happy 
>>> yppaH

但当涉及到句子的情况时,请查看下面的代码输出:

>>> Have a happy day
>>> yad yppah a evaH

但如果您只想反转字符串的字符,而不想反转字符串序列,请尝试以下操作:

a=input().split() #Splits the input on the basis of space (" ")
for b in a: #declares that var (b) is any value in the list (a)
    print(b[::-1], end=" ") #End declares to print the character in its quotes (" ") without a new line.

在上面第2行的代码中,我说**变量b是列表(a)中的任何值**我说var a是一个列表,因为当你在输入中使用split时,输入的变量变成了一个列表。还要记住,在int(input())的情况下不能使用split

输出:

>>> Have a happy day
>>> evaH a yppah yad

如果我们不在上面的代码中添加end(“”),那么它将按如下方式打印:

>>> Have a happy day
>>> evaH
>>> a
>>> yppah
>>> yad

下面是一个了解end()的示例:

代码:

for i in range(1,6):
     print(i) #Without end()

输出:

>>> 1
>>> 2
>>> 3
>>> 4
>>> 5

现在使用end()编写代码:

for i in range(1,6):
    print(i, end=" || ")

输出:

>>> 1 || 2 || 3 || 4 || 5 ||

在python中反转字符串,而不使用reversed()或[::-1]

def reverse(test):
    n = len(test)
    x=""
    for i in range(n-1,-1,-1):
        x += test[i]
    return x

作为一种不同的解决方案(因为面试中会问到):

def reverse_checker(string):
    ns = ""
    for h in range(1,len(string)+1):
        ns  += string[-h]
    print(ns)

    if ns == string:
        return True
    else:
        return False

以编程方式解决面试问题

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