How to use a reverse function in python3?

I want to reverse a string without slicing it but only using reverse function. So how can I use reverse function to reverse a string?


4 Answers
1-4 of  4
4 Answers
  • string1="hithere" #using list l1=list(string1) l1.reverse() rev="".join(l1) print rev #using reversed rev='' rev=''.join(reversed(string1)) print rev #using index rev=string1[::-1] print rev

  • With the improved support for Unicode in Python3, more and more folks will be working with languages (Arabic, Hebrew, etc.) that read right-to-left rather than left-to-right. So more and more folks will have a need to reverse a string.
    Unfortunately, Python doesn’t have a built-in function, nor do string objects have a built-in method, to do what they will want.  The obvious techniques don’t work. This:
            try:             print(1)             s = "a b c"             s = reverse(s)             print(s)         except Exception as e:             print(e)         try:             print(2)             s = "a b c"             s = reversed(s)             print(s)         except Exception as e:             print(e)         try:             print(3)             s = "a b c"             s.reverse()             print(s)         except Exception as e:             print(e)         try:             print(4)             s = "a b c"             s.reversed()             print(s)         except Exception as e:             print(e)
    produces this output
    1 name 'reverse' is not defined 2 <reversed object at 0x00BAB5F0> 3 'str' object has no attribute 'reverse' 4 'str' object has no attribute 'reversed'
    Fortunately, the solution is not too difficult. A little one-line function will do the trick.
    I call the function “rev” rather than “reverse” on the chance that Python will eventually acquire its own builtin function named “reverse”.
    def rev(s): return s[::-1]

  • You cannot use reverse() or reversed() function to reverse the string directly ,but can can reverse the string using reversed() and join() ,here is an example.

    >>> st='Text!' #text to be reversed
    >>> s=''
    >>> s.join( reversed(st) )
    '!txeT'

    The 'text!' is reversed.

  • # for string
    seqString = 'Python'
    print(list(reversed(seqString)))

    # for tuple
    seqTuple = ('P', 'y', 't', 'h', 'o', 'n')
    print(list(reversed(seqTuple)))

    # for range
    seqRange = range(5, 9)
    print(list(reversed(seqRange)))

    # for list
    seqList = [1, 2, 4, 3, 5]
    print(list(reversed(seqList)))

Python

Didn't get the answer.
Contact people of Talent-Python directly by clicking here