Reverse a string in Python
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
add a comment |
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
add a comment |
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
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
python string
edited Oct 6 '17 at 9:18
Alex Riley
80.9k26160165
80.9k26160165
asked May 31 '09 at 2:10
oneselfoneself
14k2673108
14k2673108
add a comment |
add a comment |
23 Answers
23
active
oldest
votes
How about:
>>> 'hello world'[::-1]
'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.
22
That doesn't work for utf8 though .. I needed to do this as wellb = a.decode('utf8')[::-1].encode('utf8')but thanks for the right direction !
– Ricky Levi
Apr 22 '17 at 15:18
6
@RickyLevi If.decode('utf8')is required, it meansadoes not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
add a comment |
@Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s)).
7
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
2
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
3
it's slower becausejoinhas to build the list anyway to be able to get the size.''.join(list(reversed(s)))may be slightly faster.
– Jean-François Fabre
Dec 11 '17 at 21:34
add a comment |
What is the best way of implementing a reverse function for strings?
My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:
>>> 'a string'[::-1]
'gnirts a'
or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:
>>> ''.join(reversed('a string'))
'gnirts a'
or for readability and reusability, put the slice in a function
def reversed_string(a_string):
return a_string[::-1]
and then:
>>> reversed_string('a_string')
'gnirts_a'
Longer explanation
If you're interested in the academic exposition, please keep reading.
There is no built-in reverse function in Python's str object.
Here is a couple of things about Python's strings you should know:
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.
Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[start:stop:step]
To create a slice outside of the braces, you'll need to create a slice object:
slice_obj = slice(start, stop, step)
string[slice_obj]
A readable approach:
While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
Most performant approach:
Much faster is using a reverse slice:
'foo'[::-1]
But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
Implement as Function
To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
def reversed_string(a_string):
return a_string[::-1]
And usage is simply:
reversed_string('foo')
What your teacher probably wants:
If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.
Best Practice
Theoretically better is to collect your substrings in a list, and join them later:
def reverse_a_string_more_slowly(a_string):
new_strings =
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.
Timings
Here are the timings:
>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
CPython optimizes string concatenation, whereas other implementations may not:
... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
add a comment |
Quick Answer (TL;DR)
Example
### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
Detailed Answer
Background
This answer is provided to address the following concern from @odigity:
Wow. I was horrified at first by the solution Paolo proposed, but that
took a back seat to the horror I felt upon reading the first
comment: "That's very pythonic. Good job!" I'm so disturbed that such
a bright community thinks using such cryptic methods for something so
basic is a good idea. Why isn't it just s.reverse()?
Problem
Context
- Python 2.x
- Python 3.x
Scenario:
- Developer wants to transform a string
- Transformation is to reverse order of all the characters
Solution
- example01 produces the desired result, using extended slice notation.
Pitfalls
- Developer might expect something like
string.reverse()
- The native idiomatic (aka "pythonic") solution may not be readable to newer developers
- Developer may be tempted to implement his or her own version of
string.reverse()to avoid slice notation. - The output of slice notation may be counter-intuitive in some cases:
- see e.g., example02
print 'coup_ate_grouping'[-4:] ## => 'ping'- compared to
print 'coup_ate_grouping'[-4:-1] ## => 'pin'- compared to
print 'coup_ate_grouping'[-1] ## => 'g'
- the different outcomes of indexing on
[-1]may throw some developers off
- see e.g., example02
Rationale
Python has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance.
In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
Example02
### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or start:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
Conclusion
The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.
Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.
For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.
If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.
See also
- alternate simple approach
- alternate simple approach
alternate explanation of slice notation
add a comment |
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"
add a comment |
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])
Gotta watch the recursion solution, if the string is decent length you'll run intoRecursionError: maximum recursion depth exceeded while calling a Python object. Ex:rev_string("abcdef"*1000)
– Adam Parkin
Feb 21 at 16:47
add a comment |
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
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
add a comment |
def reverse(input):
return reduce(lambda x,y : y+x, input)
2
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
add a comment |
This is also an interesting way:
def reverse_words_1(s):
rev = ''
for i in range(len(s)):
j = ~i # equivalent to j = -(i + 1)
rev += s[j]
return rev
or similar:
def reverse_words_2(s):
rev = ''
for i in reversed(range(len(s)):
rev += s[i]
return rev
Another more 'exotic' way using byterarray which supports .reverse()
b = byterarray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')`
will produce:
'!siht esreveR'
add a comment |
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
add a comment |
All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop
string ="hello,world"
for i in range(-1,-len(string)-1,-1):
print (string[i],end=(" "))
I hope this one will be helpful for someone.
add a comment |
Thats my way:
def reverse_string(string):
character_list =
for char in string:
character_list.append(char)
reversed_string = ""
for char in reversed(character_list):
reversed_string += char
return reversed_string
add a comment |
def reverse_string(string):
length = len(string)
temp = ''
for i in range(length):
temp += string[length - i - 1]
return temp
print(reverse_string('foo')) #prints "oof"
This works by looping through a string and assigning its values in reverse order to another string.
add a comment |
original = "string"
rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw
print(original)
print(rev_index)
print(''.join(rev_func))
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
add a comment |
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.
add a comment |
Recursive method:
def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
example:
print(reverse("Hello!")) #!olleH
add a comment |
Do not know about the efficiency but a short solution found on the MIT lectures is
s = "abcd"
s[-1:-(len(s)+1):-1]
Out[5]: 'dcba'
You may read more about Slices to get a better understanding of this code.
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
add a comment |
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
add a comment |
This is simple and meaningful reverse function, easy to understand and code
def reverse_sentence(text):
words = text.split(" ")
reverse =""
for word in reversed(words):
reverse += word+ " "
return reverse
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
add a comment |
s = 'Hello world'
s[::-1]
in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.
add a comment |
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)
1
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
add a comment |
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
1
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
add a comment |
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.
string = [ char for char in reversed(string)]
1
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
you need a.joinor something to make it a valid answer
– AsheKetchum
Mar 29 '17 at 15:17
BTW,[c for c in string]is tantamount tolist(string).
– Right leg
Sep 8 '17 at 12:02
add a comment |
protected by Jon Clements♦ Apr 11 '13 at 8:29
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
23 Answers
23
active
oldest
votes
23 Answers
23
active
oldest
votes
active
oldest
votes
active
oldest
votes
How about:
>>> 'hello world'[::-1]
'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.
22
That doesn't work for utf8 though .. I needed to do this as wellb = a.decode('utf8')[::-1].encode('utf8')but thanks for the right direction !
– Ricky Levi
Apr 22 '17 at 15:18
6
@RickyLevi If.decode('utf8')is required, it meansadoes not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
add a comment |
How about:
>>> 'hello world'[::-1]
'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.
22
That doesn't work for utf8 though .. I needed to do this as wellb = a.decode('utf8')[::-1].encode('utf8')but thanks for the right direction !
– Ricky Levi
Apr 22 '17 at 15:18
6
@RickyLevi If.decode('utf8')is required, it meansadoes not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
add a comment |
How about:
>>> 'hello world'[::-1]
'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.
How about:
>>> 'hello world'[::-1]
'dlrow olleh'
This is extended slice syntax. It works by doing [begin:end:step] - by leaving begin and end off and specifying a step of -1, it reverses a string.
edited Feb 25 '14 at 2:13
Mokolodi1
7910
7910
answered May 31 '09 at 2:11
Paolo BergantinoPaolo Bergantino
381k73491426
381k73491426
22
That doesn't work for utf8 though .. I needed to do this as wellb = a.decode('utf8')[::-1].encode('utf8')but thanks for the right direction !
– Ricky Levi
Apr 22 '17 at 15:18
6
@RickyLevi If.decode('utf8')is required, it meansadoes not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
add a comment |
22
That doesn't work for utf8 though .. I needed to do this as wellb = a.decode('utf8')[::-1].encode('utf8')but thanks for the right direction !
– Ricky Levi
Apr 22 '17 at 15:18
6
@RickyLevi If.decode('utf8')is required, it meansadoes not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
22
22
That doesn't work for utf8 though .. I needed to do this as well
b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !– Ricky Levi
Apr 22 '17 at 15:18
That doesn't work for utf8 though .. I needed to do this as well
b = a.decode('utf8')[::-1].encode('utf8') but thanks for the right direction !– Ricky Levi
Apr 22 '17 at 15:18
6
6
@RickyLevi If
.decode('utf8') is required, it means a does not contain any string objects, rather bytes.– Shiplu Mokaddim
Nov 1 '17 at 18:43
@RickyLevi If
.decode('utf8') is required, it means a does not contain any string objects, rather bytes.– Shiplu Mokaddim
Nov 1 '17 at 18:43
add a comment |
@Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s)).
7
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
2
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
3
it's slower becausejoinhas to build the list anyway to be able to get the size.''.join(list(reversed(s)))may be slightly faster.
– Jean-François Fabre
Dec 11 '17 at 21:34
add a comment |
@Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s)).
7
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
2
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
3
it's slower becausejoinhas to build the list anyway to be able to get the size.''.join(list(reversed(s)))may be slightly faster.
– Jean-François Fabre
Dec 11 '17 at 21:34
add a comment |
@Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s)).
@Paolo's s[::-1] is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s)).
edited Nov 29 '14 at 18:28
zadrozny
3931619
3931619
answered May 31 '09 at 2:13
Alex MartelliAlex Martelli
629k12810401280
629k12810401280
7
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
2
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
3
it's slower becausejoinhas to build the list anyway to be able to get the size.''.join(list(reversed(s)))may be slightly faster.
– Jean-François Fabre
Dec 11 '17 at 21:34
add a comment |
7
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
2
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
3
it's slower becausejoinhas to build the list anyway to be able to get the size.''.join(list(reversed(s)))may be slightly faster.
– Jean-François Fabre
Dec 11 '17 at 21:34
7
7
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
This is about 3 times slower.
– oneself
Oct 6 '17 at 15:09
2
2
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
And a quick comment to say what it does will explain it better than using this slower version!
– tburrows13
Nov 2 '17 at 22:04
3
3
it's slower because
join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.– Jean-François Fabre
Dec 11 '17 at 21:34
it's slower because
join has to build the list anyway to be able to get the size. ''.join(list(reversed(s))) may be slightly faster.– Jean-François Fabre
Dec 11 '17 at 21:34
add a comment |
What is the best way of implementing a reverse function for strings?
My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:
>>> 'a string'[::-1]
'gnirts a'
or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:
>>> ''.join(reversed('a string'))
'gnirts a'
or for readability and reusability, put the slice in a function
def reversed_string(a_string):
return a_string[::-1]
and then:
>>> reversed_string('a_string')
'gnirts_a'
Longer explanation
If you're interested in the academic exposition, please keep reading.
There is no built-in reverse function in Python's str object.
Here is a couple of things about Python's strings you should know:
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.
Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[start:stop:step]
To create a slice outside of the braces, you'll need to create a slice object:
slice_obj = slice(start, stop, step)
string[slice_obj]
A readable approach:
While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
Most performant approach:
Much faster is using a reverse slice:
'foo'[::-1]
But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
Implement as Function
To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
def reversed_string(a_string):
return a_string[::-1]
And usage is simply:
reversed_string('foo')
What your teacher probably wants:
If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.
Best Practice
Theoretically better is to collect your substrings in a list, and join them later:
def reverse_a_string_more_slowly(a_string):
new_strings =
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.
Timings
Here are the timings:
>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
CPython optimizes string concatenation, whereas other implementations may not:
... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
add a comment |
What is the best way of implementing a reverse function for strings?
My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:
>>> 'a string'[::-1]
'gnirts a'
or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:
>>> ''.join(reversed('a string'))
'gnirts a'
or for readability and reusability, put the slice in a function
def reversed_string(a_string):
return a_string[::-1]
and then:
>>> reversed_string('a_string')
'gnirts_a'
Longer explanation
If you're interested in the academic exposition, please keep reading.
There is no built-in reverse function in Python's str object.
Here is a couple of things about Python's strings you should know:
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.
Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[start:stop:step]
To create a slice outside of the braces, you'll need to create a slice object:
slice_obj = slice(start, stop, step)
string[slice_obj]
A readable approach:
While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
Most performant approach:
Much faster is using a reverse slice:
'foo'[::-1]
But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
Implement as Function
To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
def reversed_string(a_string):
return a_string[::-1]
And usage is simply:
reversed_string('foo')
What your teacher probably wants:
If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.
Best Practice
Theoretically better is to collect your substrings in a list, and join them later:
def reverse_a_string_more_slowly(a_string):
new_strings =
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.
Timings
Here are the timings:
>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
CPython optimizes string concatenation, whereas other implementations may not:
... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
add a comment |
What is the best way of implementing a reverse function for strings?
My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:
>>> 'a string'[::-1]
'gnirts a'
or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:
>>> ''.join(reversed('a string'))
'gnirts a'
or for readability and reusability, put the slice in a function
def reversed_string(a_string):
return a_string[::-1]
and then:
>>> reversed_string('a_string')
'gnirts_a'
Longer explanation
If you're interested in the academic exposition, please keep reading.
There is no built-in reverse function in Python's str object.
Here is a couple of things about Python's strings you should know:
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.
Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[start:stop:step]
To create a slice outside of the braces, you'll need to create a slice object:
slice_obj = slice(start, stop, step)
string[slice_obj]
A readable approach:
While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
Most performant approach:
Much faster is using a reverse slice:
'foo'[::-1]
But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
Implement as Function
To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
def reversed_string(a_string):
return a_string[::-1]
And usage is simply:
reversed_string('foo')
What your teacher probably wants:
If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.
Best Practice
Theoretically better is to collect your substrings in a list, and join them later:
def reverse_a_string_more_slowly(a_string):
new_strings =
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.
Timings
Here are the timings:
>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
CPython optimizes string concatenation, whereas other implementations may not:
... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
What is the best way of implementing a reverse function for strings?
My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:
>>> 'a string'[::-1]
'gnirts a'
or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:
>>> ''.join(reversed('a string'))
'gnirts a'
or for readability and reusability, put the slice in a function
def reversed_string(a_string):
return a_string[::-1]
and then:
>>> reversed_string('a_string')
'gnirts_a'
Longer explanation
If you're interested in the academic exposition, please keep reading.
There is no built-in reverse function in Python's str object.
Here is a couple of things about Python's strings you should know:
In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.
Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:
string[subscript]
The subscript creates a slice by including a colon within the braces:
string[start:stop:step]
To create a slice outside of the braces, you'll need to create a slice object:
slice_obj = slice(start, stop, step)
string[slice_obj]
A readable approach:
While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:
def reverse_string_readable_answer(string):
return ''.join(reversed(string))
Most performant approach:
Much faster is using a reverse slice:
'foo'[::-1]
But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.
start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]
Implement as Function
To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:
def reversed_string(a_string):
return a_string[::-1]
And usage is simply:
reversed_string('foo')
What your teacher probably wants:
If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:
def reverse_a_string_slowly(a_string):
new_string = ''
index = len(a_string)
while index:
index -= 1 # index = index - 1
new_string += a_string[index] # new_string = new_string + character
return new_string
This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.
Best Practice
Theoretically better is to collect your substrings in a list, and join them later:
def reverse_a_string_more_slowly(a_string):
new_strings =
index = len(a_string)
while index:
index -= 1
new_strings.append(a_string[index])
return ''.join(new_strings)
However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.
Timings
Here are the timings:
>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265
CPython optimizes string concatenation, whereas other implementations may not:
... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.
edited Sep 27 '17 at 16:14
answered Jan 8 '15 at 15:32
Aaron Hall♦Aaron Hall
177k51305255
177k51305255
add a comment |
add a comment |
Quick Answer (TL;DR)
Example
### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
Detailed Answer
Background
This answer is provided to address the following concern from @odigity:
Wow. I was horrified at first by the solution Paolo proposed, but that
took a back seat to the horror I felt upon reading the first
comment: "That's very pythonic. Good job!" I'm so disturbed that such
a bright community thinks using such cryptic methods for something so
basic is a good idea. Why isn't it just s.reverse()?
Problem
Context
- Python 2.x
- Python 3.x
Scenario:
- Developer wants to transform a string
- Transformation is to reverse order of all the characters
Solution
- example01 produces the desired result, using extended slice notation.
Pitfalls
- Developer might expect something like
string.reverse()
- The native idiomatic (aka "pythonic") solution may not be readable to newer developers
- Developer may be tempted to implement his or her own version of
string.reverse()to avoid slice notation. - The output of slice notation may be counter-intuitive in some cases:
- see e.g., example02
print 'coup_ate_grouping'[-4:] ## => 'ping'- compared to
print 'coup_ate_grouping'[-4:-1] ## => 'pin'- compared to
print 'coup_ate_grouping'[-1] ## => 'g'
- the different outcomes of indexing on
[-1]may throw some developers off
- see e.g., example02
Rationale
Python has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance.
In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
Example02
### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or start:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
Conclusion
The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.
Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.
For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.
If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.
See also
- alternate simple approach
- alternate simple approach
alternate explanation of slice notation
add a comment |
Quick Answer (TL;DR)
Example
### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
Detailed Answer
Background
This answer is provided to address the following concern from @odigity:
Wow. I was horrified at first by the solution Paolo proposed, but that
took a back seat to the horror I felt upon reading the first
comment: "That's very pythonic. Good job!" I'm so disturbed that such
a bright community thinks using such cryptic methods for something so
basic is a good idea. Why isn't it just s.reverse()?
Problem
Context
- Python 2.x
- Python 3.x
Scenario:
- Developer wants to transform a string
- Transformation is to reverse order of all the characters
Solution
- example01 produces the desired result, using extended slice notation.
Pitfalls
- Developer might expect something like
string.reverse()
- The native idiomatic (aka "pythonic") solution may not be readable to newer developers
- Developer may be tempted to implement his or her own version of
string.reverse()to avoid slice notation. - The output of slice notation may be counter-intuitive in some cases:
- see e.g., example02
print 'coup_ate_grouping'[-4:] ## => 'ping'- compared to
print 'coup_ate_grouping'[-4:-1] ## => 'pin'- compared to
print 'coup_ate_grouping'[-1] ## => 'g'
- the different outcomes of indexing on
[-1]may throw some developers off
- see e.g., example02
Rationale
Python has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance.
In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
Example02
### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or start:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
Conclusion
The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.
Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.
For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.
If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.
See also
- alternate simple approach
- alternate simple approach
alternate explanation of slice notation
add a comment |
Quick Answer (TL;DR)
Example
### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
Detailed Answer
Background
This answer is provided to address the following concern from @odigity:
Wow. I was horrified at first by the solution Paolo proposed, but that
took a back seat to the horror I felt upon reading the first
comment: "That's very pythonic. Good job!" I'm so disturbed that such
a bright community thinks using such cryptic methods for something so
basic is a good idea. Why isn't it just s.reverse()?
Problem
Context
- Python 2.x
- Python 3.x
Scenario:
- Developer wants to transform a string
- Transformation is to reverse order of all the characters
Solution
- example01 produces the desired result, using extended slice notation.
Pitfalls
- Developer might expect something like
string.reverse()
- The native idiomatic (aka "pythonic") solution may not be readable to newer developers
- Developer may be tempted to implement his or her own version of
string.reverse()to avoid slice notation. - The output of slice notation may be counter-intuitive in some cases:
- see e.g., example02
print 'coup_ate_grouping'[-4:] ## => 'ping'- compared to
print 'coup_ate_grouping'[-4:-1] ## => 'pin'- compared to
print 'coup_ate_grouping'[-1] ## => 'g'
- the different outcomes of indexing on
[-1]may throw some developers off
- see e.g., example02
Rationale
Python has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance.
In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
Example02
### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or start:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
Conclusion
The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.
Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.
For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.
If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.
See also
- alternate simple approach
- alternate simple approach
alternate explanation of slice notation
Quick Answer (TL;DR)
Example
### example01 -------------------
mystring = 'coup_ate_grouping'
backwards = mystring[::-1]
print backwards
### ... or even ...
mystring = 'coup_ate_grouping'[::-1]
print mystring
### result01 -------------------
'''
gnipuorg_eta_puoc
'''
Detailed Answer
Background
This answer is provided to address the following concern from @odigity:
Wow. I was horrified at first by the solution Paolo proposed, but that
took a back seat to the horror I felt upon reading the first
comment: "That's very pythonic. Good job!" I'm so disturbed that such
a bright community thinks using such cryptic methods for something so
basic is a good idea. Why isn't it just s.reverse()?
Problem
Context
- Python 2.x
- Python 3.x
Scenario:
- Developer wants to transform a string
- Transformation is to reverse order of all the characters
Solution
- example01 produces the desired result, using extended slice notation.
Pitfalls
- Developer might expect something like
string.reverse()
- The native idiomatic (aka "pythonic") solution may not be readable to newer developers
- Developer may be tempted to implement his or her own version of
string.reverse()to avoid slice notation. - The output of slice notation may be counter-intuitive in some cases:
- see e.g., example02
print 'coup_ate_grouping'[-4:] ## => 'ping'- compared to
print 'coup_ate_grouping'[-4:-1] ## => 'pin'- compared to
print 'coup_ate_grouping'[-1] ## => 'g'
- the different outcomes of indexing on
[-1]may throw some developers off
- see e.g., example02
Rationale
Python has a special circumstance to be aware of: a string is an iterable type.
One rationale for excluding a string.reverse() method is to give python developers incentive to leverage the power of this special circumstance.
In simplified terms, this simply means each individual character in a string can be easily operated on as a part of a sequential arrangement of elements, just like arrays in other programming languages.
To understand how this works, reviewing example02 can provide a good overview.
Example02
### example02 -------------------
## start (with positive integers)
print 'coup_ate_grouping'[0] ## => 'c'
print 'coup_ate_grouping'[1] ## => 'o'
print 'coup_ate_grouping'[2] ## => 'u'
## start (with negative integers)
print 'coup_ate_grouping'[-1] ## => 'g'
print 'coup_ate_grouping'[-2] ## => 'n'
print 'coup_ate_grouping'[-3] ## => 'i'
## start:end
print 'coup_ate_grouping'[0:4] ## => 'coup'
print 'coup_ate_grouping'[4:8] ## => '_ate'
print 'coup_ate_grouping'[8:12] ## => '_gro'
## start:end
print 'coup_ate_grouping'[-4:] ## => 'ping' (counter-intuitive)
print 'coup_ate_grouping'[-4:-1] ## => 'pin'
print 'coup_ate_grouping'[-4:-2] ## => 'pi'
print 'coup_ate_grouping'[-4:-3] ## => 'p'
print 'coup_ate_grouping'[-4:-4] ## => ''
print 'coup_ate_grouping'[0:-1] ## => 'coup_ate_groupin'
print 'coup_ate_grouping'[0:] ## => 'coup_ate_grouping' (counter-intuitive)
## start:end:step (or start:end:stride)
print 'coup_ate_grouping'[-1::1] ## => 'g'
print 'coup_ate_grouping'[-1::-1] ## => 'gnipuorg_eta_puoc'
## combinations
print 'coup_ate_grouping'[-1::-1][-4:] ## => 'puoc'
Conclusion
The cognitive load associated with understanding how slice notation works in python may indeed be too much for some adopters and developers who do not wish to invest much time in learning the language.
Nevertheless, once the basic principles are understood, the power of this approach over fixed string manipulation methods can be quite favorable.
For those who think otherwise, there are alternate approaches, such as lambda functions, iterators, or simple one-off function declarations.
If desired, a developer can implement her own string.reverse() method, however it is good to understand the rationale behind this aspect of python.
See also
- alternate simple approach
- alternate simple approach
alternate explanation of slice notation
edited Apr 16 '18 at 17:42
answered Oct 31 '15 at 22:24
dreftymacdreftymac
16k2190153
16k2190153
add a comment |
add a comment |
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"
add a comment |
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"
add a comment |
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"
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"
answered Apr 1 '16 at 7:49
pX0rpX0r
65069
65069
add a comment |
add a comment |
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])
Gotta watch the recursion solution, if the string is decent length you'll run intoRecursionError: maximum recursion depth exceeded while calling a Python object. Ex:rev_string("abcdef"*1000)
– Adam Parkin
Feb 21 at 16:47
add a comment |
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])
Gotta watch the recursion solution, if the string is decent length you'll run intoRecursionError: maximum recursion depth exceeded while calling a Python object. Ex:rev_string("abcdef"*1000)
– Adam Parkin
Feb 21 at 16:47
add a comment |
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])
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])
answered May 20 '18 at 22:24
harryharry
135115
135115
Gotta watch the recursion solution, if the string is decent length you'll run intoRecursionError: maximum recursion depth exceeded while calling a Python object. Ex:rev_string("abcdef"*1000)
– Adam Parkin
Feb 21 at 16:47
add a comment |
Gotta watch the recursion solution, if the string is decent length you'll run intoRecursionError: maximum recursion depth exceeded while calling a Python object. Ex:rev_string("abcdef"*1000)
– Adam Parkin
Feb 21 at 16:47
Gotta watch the recursion solution, if the string is decent length you'll run into
RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)– Adam Parkin
Feb 21 at 16:47
Gotta watch the recursion solution, if the string is decent length you'll run into
RecursionError: maximum recursion depth exceeded while calling a Python object. Ex: rev_string("abcdef"*1000)– Adam Parkin
Feb 21 at 16:47
add a comment |
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
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
add a comment |
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
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
add a comment |
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
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
answered Dec 10 '14 at 12:57
akshaynagpalakshaynagpal
1,1481923
1,1481923
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
add a comment |
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
1
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 '18 at 15:32
add a comment |
def reverse(input):
return reduce(lambda x,y : y+x, input)
2
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
add a comment |
def reverse(input):
return reduce(lambda x,y : y+x, input)
2
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
add a comment |
def reverse(input):
return reduce(lambda x,y : y+x, input)
def reverse(input):
return reduce(lambda x,y : y+x, input)
edited Jun 26 '15 at 4:56
josliber♦
37.4k1164101
37.4k1164101
answered Jun 26 '15 at 4:25
JavierJavier
473313
473313
2
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
add a comment |
2
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
2
2
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
I clicked upvote, because I like this lambda expression. Unfortunately, it's the least efficient solution from all listed above (test: Gist palindrome.py )
– oski86
Jul 24 '15 at 16:32
add a comment |
This is also an interesting way:
def reverse_words_1(s):
rev = ''
for i in range(len(s)):
j = ~i # equivalent to j = -(i + 1)
rev += s[j]
return rev
or similar:
def reverse_words_2(s):
rev = ''
for i in reversed(range(len(s)):
rev += s[i]
return rev
Another more 'exotic' way using byterarray which supports .reverse()
b = byterarray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')`
will produce:
'!siht esreveR'
add a comment |
This is also an interesting way:
def reverse_words_1(s):
rev = ''
for i in range(len(s)):
j = ~i # equivalent to j = -(i + 1)
rev += s[j]
return rev
or similar:
def reverse_words_2(s):
rev = ''
for i in reversed(range(len(s)):
rev += s[i]
return rev
Another more 'exotic' way using byterarray which supports .reverse()
b = byterarray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')`
will produce:
'!siht esreveR'
add a comment |
This is also an interesting way:
def reverse_words_1(s):
rev = ''
for i in range(len(s)):
j = ~i # equivalent to j = -(i + 1)
rev += s[j]
return rev
or similar:
def reverse_words_2(s):
rev = ''
for i in reversed(range(len(s)):
rev += s[i]
return rev
Another more 'exotic' way using byterarray which supports .reverse()
b = byterarray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')`
will produce:
'!siht esreveR'
This is also an interesting way:
def reverse_words_1(s):
rev = ''
for i in range(len(s)):
j = ~i # equivalent to j = -(i + 1)
rev += s[j]
return rev
or similar:
def reverse_words_2(s):
rev = ''
for i in reversed(range(len(s)):
rev += s[i]
return rev
Another more 'exotic' way using byterarray which supports .reverse()
b = byterarray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')`
will produce:
'!siht esreveR'
edited Sep 25 '18 at 13:57
answered Sep 25 '18 at 11:46
mdnmdn
33339
33339
add a comment |
add a comment |
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
add a comment |
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
add a comment |
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
answered May 4 '15 at 17:02
buzhidaobuzhidao
776626
776626
add a comment |
add a comment |
All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop
string ="hello,world"
for i in range(-1,-len(string)-1,-1):
print (string[i],end=(" "))
I hope this one will be helpful for someone.
add a comment |
All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop
string ="hello,world"
for i in range(-1,-len(string)-1,-1):
print (string[i],end=(" "))
I hope this one will be helpful for someone.
add a comment |
All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop
string ="hello,world"
for i in range(-1,-len(string)-1,-1):
print (string[i],end=(" "))
I hope this one will be helpful for someone.
All of the above solutions are perfect but if we are trying to reverse a string using for loop in python will became a little bit tricky so here is how we can reverse a string using for loop
string ="hello,world"
for i in range(-1,-len(string)-1,-1):
print (string[i],end=(" "))
I hope this one will be helpful for someone.
edited Apr 16 '18 at 20:46
answered Apr 16 '18 at 20:38
Nitin KhannaNitin Khanna
503312
503312
add a comment |
add a comment |
Thats my way:
def reverse_string(string):
character_list =
for char in string:
character_list.append(char)
reversed_string = ""
for char in reversed(character_list):
reversed_string += char
return reversed_string
add a comment |
Thats my way:
def reverse_string(string):
character_list =
for char in string:
character_list.append(char)
reversed_string = ""
for char in reversed(character_list):
reversed_string += char
return reversed_string
add a comment |
Thats my way:
def reverse_string(string):
character_list =
for char in string:
character_list.append(char)
reversed_string = ""
for char in reversed(character_list):
reversed_string += char
return reversed_string
Thats my way:
def reverse_string(string):
character_list =
for char in string:
character_list.append(char)
reversed_string = ""
for char in reversed(character_list):
reversed_string += char
return reversed_string
answered Oct 28 '18 at 11:51
AlexAlex
214
214
add a comment |
add a comment |
def reverse_string(string):
length = len(string)
temp = ''
for i in range(length):
temp += string[length - i - 1]
return temp
print(reverse_string('foo')) #prints "oof"
This works by looping through a string and assigning its values in reverse order to another string.
add a comment |
def reverse_string(string):
length = len(string)
temp = ''
for i in range(length):
temp += string[length - i - 1]
return temp
print(reverse_string('foo')) #prints "oof"
This works by looping through a string and assigning its values in reverse order to another string.
add a comment |
def reverse_string(string):
length = len(string)
temp = ''
for i in range(length):
temp += string[length - i - 1]
return temp
print(reverse_string('foo')) #prints "oof"
This works by looping through a string and assigning its values in reverse order to another string.
def reverse_string(string):
length = len(string)
temp = ''
for i in range(length):
temp += string[length - i - 1]
return temp
print(reverse_string('foo')) #prints "oof"
This works by looping through a string and assigning its values in reverse order to another string.
answered Dec 10 '18 at 18:23
Supa Mega Ducky Momo da WaffleSupa Mega Ducky Momo da Waffle
1
1
add a comment |
add a comment |
original = "string"
rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw
print(original)
print(rev_index)
print(''.join(rev_func))
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
add a comment |
original = "string"
rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw
print(original)
print(rev_index)
print(''.join(rev_func))
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
add a comment |
original = "string"
rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw
print(original)
print(rev_index)
print(''.join(rev_func))
original = "string"
rev_index = original[::-1]
rev_func = list(reversed(list(original))) #nsfw
print(original)
print(rev_index)
print(''.join(rev_func))
answered Dec 29 '18 at 0:42
JEXJEX
414
414
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
add a comment |
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
While this code may answer the question, it is better to explain how to solve the problem and provide the code as an example or reference. Code-only answers can be confusing and lack context.
– Robert Columbia
Dec 29 '18 at 11:11
add a comment |
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.
add a comment |
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.
add a comment |
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.
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.
answered Dec 29 '15 at 13:23
Claudiu CreangaClaudiu Creanga
3,80683275
3,80683275
add a comment |
add a comment |
Recursive method:
def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
example:
print(reverse("Hello!")) #!olleH
add a comment |
Recursive method:
def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
example:
print(reverse("Hello!")) #!olleH
add a comment |
Recursive method:
def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
example:
print(reverse("Hello!")) #!olleH
Recursive method:
def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
example:
print(reverse("Hello!")) #!olleH
answered Jan 13 '18 at 14:21
mattmatt
405316
405316
add a comment |
add a comment |
Do not know about the efficiency but a short solution found on the MIT lectures is
s = "abcd"
s[-1:-(len(s)+1):-1]
Out[5]: 'dcba'
You may read more about Slices to get a better understanding of this code.
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
add a comment |
Do not know about the efficiency but a short solution found on the MIT lectures is
s = "abcd"
s[-1:-(len(s)+1):-1]
Out[5]: 'dcba'
You may read more about Slices to get a better understanding of this code.
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
add a comment |
Do not know about the efficiency but a short solution found on the MIT lectures is
s = "abcd"
s[-1:-(len(s)+1):-1]
Out[5]: 'dcba'
You may read more about Slices to get a better understanding of this code.
Do not know about the efficiency but a short solution found on the MIT lectures is
s = "abcd"
s[-1:-(len(s)+1):-1]
Out[5]: 'dcba'
You may read more about Slices to get a better understanding of this code.
edited Feb 18 at 7:27
answered Feb 18 at 7:22
Krishnadas PCKrishnadas PC
1,9571719
1,9571719
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
add a comment |
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
Why would you include the start & stop, if the goal is to just reverse the string?
– Adam Parkin
Feb 21 at 16:34
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
@Adam This one I got from MIT lectures. Not created by me.
– Krishnadas PC
Feb 21 at 17:15
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Mar 8 '17 at 12:10
Chowdeswara RaoChowdeswara Rao
93
93
add a comment |
add a comment |
This is simple and meaningful reverse function, easy to understand and code
def reverse_sentence(text):
words = text.split(" ")
reverse =""
for word in reversed(words):
reverse += word+ " "
return reverse
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
add a comment |
This is simple and meaningful reverse function, easy to understand and code
def reverse_sentence(text):
words = text.split(" ")
reverse =""
for word in reversed(words):
reverse += word+ " "
return reverse
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
add a comment |
This is simple and meaningful reverse function, easy to understand and code
def reverse_sentence(text):
words = text.split(" ")
reverse =""
for word in reversed(words):
reverse += word+ " "
return reverse
This is simple and meaningful reverse function, easy to understand and code
def reverse_sentence(text):
words = text.split(" ")
reverse =""
for word in reversed(words):
reverse += word+ " "
return reverse
answered Sep 2 '18 at 10:03
Kiran SkKiran Sk
403321
403321
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
add a comment |
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
While this might answer the authors question, it lacks some explaining words and/or links to documentation. Raw code snippets are not very helpful without some phrases around them. You may also find how to write a good answer very helpful. Please edit your answer.
– hellow
Nov 11 '18 at 7:21
add a comment |
s = 'Hello world'
s[::-1]
in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.
add a comment |
s = 'Hello world'
s[::-1]
in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.
add a comment |
s = 'Hello world'
s[::-1]
in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.
s = 'Hello world'
s[::-1]
in the above example label s or variable s is holding string which contain Hello world string and on second step i m printing reverse of Hello world string by taking starting from everything to everything in reverse step order with -1.
answered Jan 13 '18 at 14:58
user128364user128364
1,1301110
1,1301110
add a comment |
add a comment |
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)
1
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
add a comment |
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)
1
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
add a comment |
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)
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)
answered Feb 3 '16 at 10:40
olgaolga
446
446
1
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
add a comment |
1
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
1
1
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
It is not a nice solution to have such a long code for such a trivial task.
– Hunter_71
Oct 9 '17 at 23:14
add a comment |
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
1
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
add a comment |
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
1
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
add a comment |
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
s = 'hello'
ln = len(s)
i = 1
while True:
rev = s[ln-i]
print rev,
i = i + 1
if i == ln + 1 :
break
OUTPUT :
o l l e h
edited Sep 22 '16 at 11:03
Kalpesh Dusane
1,05421425
1,05421425
answered Mar 24 '16 at 18:28
sudistacksudistack
9714
9714
1
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
add a comment |
1
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
1
1
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
what is the point of using a while loop here?
– AsheKetchum
Mar 29 '17 at 15:18
add a comment |
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.
string = [ char for char in reversed(string)]
1
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
you need a.joinor something to make it a valid answer
– AsheKetchum
Mar 29 '17 at 15:17
BTW,[c for c in string]is tantamount tolist(string).
– Right leg
Sep 8 '17 at 12:02
add a comment |
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.
string = [ char for char in reversed(string)]
1
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
you need a.joinor something to make it a valid answer
– AsheKetchum
Mar 29 '17 at 15:17
BTW,[c for c in string]is tantamount tolist(string).
– Right leg
Sep 8 '17 at 12:02
add a comment |
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.
string = [ char for char in reversed(string)]
You can use the reversed function with a list comprehesive. But I don't understand why this method was eliminated in python 3, was unnecessarily.
string = [ char for char in reversed(string)]
answered Jul 19 '16 at 17:32
alejandro izquierdoalejandro izquierdo
244
244
1
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
you need a.joinor something to make it a valid answer
– AsheKetchum
Mar 29 '17 at 15:17
BTW,[c for c in string]is tantamount tolist(string).
– Right leg
Sep 8 '17 at 12:02
add a comment |
1
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
you need a.joinor something to make it a valid answer
– AsheKetchum
Mar 29 '17 at 15:17
BTW,[c for c in string]is tantamount tolist(string).
– Right leg
Sep 8 '17 at 12:02
1
1
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
What was eliminated? This continues to work just fine in Py3...
– ShadowRanger
Nov 4 '16 at 5:54
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
The question asks for the reverse of a string, and you instead give a list??
– user21820
Feb 25 '17 at 13:47
you need a
.join or something to make it a valid answer– AsheKetchum
Mar 29 '17 at 15:17
you need a
.join or something to make it a valid answer– AsheKetchum
Mar 29 '17 at 15:17
BTW,
[c for c in string] is tantamount to list(string).– Right leg
Sep 8 '17 at 12:02
BTW,
[c for c in string] is tantamount to list(string).– Right leg
Sep 8 '17 at 12:02
add a comment |
protected by Jon Clements♦ Apr 11 '13 at 8:29
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?