Reverse a string in Python

2018-12-31 00:44发布

There is no built in reverse function for Python's str object. What is the best way of implementing this method?

If supplying a very concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.

标签: python string
22条回答
唯独是你
2楼-- · 2018-12-31 01:12

Here is simply:

print "loremipsum"[-1::-1]

and some logically:

def str_reverse_fun():
    empty_list = []
    new_str = 'loremipsum'
    index = len(new_str)
    while index:
        index = index - 1
        empty_list.append(new_str[index])
    return ''.join(empty_list)
print str_reverse_fun()

output:

muspimerol

查看更多
素衣白纱
3楼-- · 2018-12-31 01:15

A lesser perplexing way to look at it would be:

string = 'happy'
print(string)

'happy'

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

'yppah'

In English [-1::-1] reads as:

"Starting at -1, go all the way, taking steps of -1"

查看更多
梦醉为红颜
4楼-- · 2018-12-31 01:15

using slice notation

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

using reversed() function

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

using recursion

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

    return s[-1] + rev_string(s[:-1])
查看更多
回忆,回不去的记忆
5楼-- · 2018-12-31 01:17

Sure, in Python you can do very fancy 1-line stuff. :)
Here's a simple, all rounder solution that could work in any programming language.

def reverse_string(phrase):
    reversed = ""
    length = len(phrase)
    for i in range(length):
        reversed += phrase[length-1-i]
    return reversed

phrase = raw_input("Provide a string: ")
print reverse_string(phrase)
查看更多
何处买醉
6楼-- · 2018-12-31 01:18

Reverse a string in python without using reversed() or [::-1]

def reverse(test):
    n = len(test)
    x=""
    for i in range(n-1,-1,-1):
        x += test[i]
    return x
查看更多
不再属于我。
7楼-- · 2018-12-31 01:18

Here is one without [::-1] or reversed (for learning purposes):

def reverse(text):
    new_string = []
    n = len(text)
    while (n > 0):
        new_string.append(text[n-1])
        n -= 1
    return ''.join(new_string)
print reverse("abcd")

you can use += to concatenate strings but join() is faster.

查看更多
登录 后发表回答