-4

I want to know how can I reverse a string without using any library modules or even a dummy variable or extended slice notation e.g. s[::-1]

for example I have a string >>>['f','a','l','u','b']

output should be >>>['b','u','l','a','f']

I have searched these two links but they dont provide this solution

String reversal in Python

Reverse a string in Python

Python reversing a string using recursion

these links don't provide the answer. I know strings are immutable that's exactly why I used string characters in list, and almost everyone here solved it using builtin functions (which I already know). Still no concrete answer

This question was asked to me in an interview. And I think its better to encourage new comers rather than castigating and down voting their questions

Community
  • 1
  • 1
Saad
  • 1,856
  • 1
  • 22
  • 28

4 Answers4

3

As @Chris mentioned in the comments,

seq = ['f','a','l','u','b'] # this is a list not a string

so you can easily reverse a list in-place

seq.reverse()
jamylak
  • 128,818
  • 30
  • 231
  • 230
1
s = 'falub'
s = ''.join(reversed(s))

or

list(reversed(s)) 

if you want to keep it as a list.

Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • Without dummy variables, so would need to assign back to s. No need to call list, though, unless (and the OP is unclear) the output should be a list. – selllikesybok Aug 03 '12 at 13:40
1

You can use this to reverse without the slice notation, no need for a call to list()

s = "hello world"
s_reversed = ''.join(reversed(s))

// output
'dlrow olleh'
Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • 1
    Hopefully the OP can piece together how to do it in one step on their own – Hunter McMillen Aug 03 '12 at 13:40
  • Given that the question was asked in the first place, is this a safe assumption? Took me 1 minute to find the answer on my own (it's just such a weird thing to do, why NOT use slice notation?), and 2 more to find a thread from 2009 discussing the same question. – selllikesybok Aug 03 '12 at 13:42
  • OP did post some links which included this method so he must be confused... – jamylak Aug 03 '12 at 13:44
1

There may be some crazy bitwise operation you can do, but that is not my forte. Since I wouldn't consider built-in functions "library modules", then I think you could do this:

my_str = "".join(reversed(my_str))

But you would really never want to do this.

ETA: Actually, having looked into it, looks like the "crazy bitwise" solution to this problem is actually much more complicated and may required library modules.

selllikesybok
  • 1,250
  • 11
  • 17