Best way to loop over a python string backwards

后端 未结 11 1791
無奈伤痛
無奈伤痛 2020-12-03 02:16

What is the best way to loop over a python string backwards?

The following seems a little awkward for all the need of -1 offset:

string = \"trick or          


        
相关标签:
11条回答
  • 2020-12-03 02:51

    string reverse

    def reverse(a_string):
        rev = ''
        for i in range(len(a_string)-1, -1, -1):
            rev = rev + a_string[i]
        return rev
    print(reverse("This string should be reversed!"))
    

    output is: !desrever eb dluohs gnirts sihT

    0 讨论(0)
  • 2020-12-03 02:52
     string = "trick or treat"
     for c in string[::-1]:
         print c
    

    I would use that. It is probably quite fast although there may be a slightly better way (but I doubt it).

    EDIT: Actually, with a second test using a program I hacked together, reversed is probably the way to go.

     ==== Results ====
    Sample 1: 0.0225071907043 # Using a for loop
    Sample 2: 0.0100858211517 # Using reversed
    
    0 讨论(0)
  • 2020-12-03 02:55
    def reverse(text):
        x = ""
        for i in range(len(text)):
            x = x + text[len(text)-i-1]
        return x
    
    0 讨论(0)
  • 2020-12-03 03:03

    Reverse a String in Python using For Loop

    outputStr = ''
    a = raw_input("Enter String: ")
    for i in range(len(a), 0, -1):
        outputStr += a[i-1]
    print outputStr
    
    0 讨论(0)
  • 2020-12-03 03:06
    string = "trick or treat"
    for c in reversed(string):
        print c
    

    Will do what I think you want. It uses an iterator. This should work with anything that has __reveresed__() or __len__() and __getitem__() implemented. __getitem__() would have to take int arguments starting at 0.

    0 讨论(0)
  • 2020-12-03 03:07

    Here is a way to reverse a string without utilizing the built in features such as reversed. Negative step values traverse backwards.

    def reverse(text):
        rev = ''
        for i in range(len(text), 0, -1):
            rev += text[i-1]
        return rev
    
    0 讨论(0)
提交回复
热议问题