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
76.9k21156161
76.9k21156161
asked May 31 '09 at 2:10
oneself
13.6k2573104
13.6k2573104
add a comment |
add a comment |
21 Answers
21
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.
20
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 meansa
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))
.
6
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 becausejoin
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 |
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])
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 at 15:32
add a comment |
def reverse(input):
return reduce(lambda x,y : y+x, input)
1
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 |
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 |
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 |
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 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.join
or 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?
21 Answers
21
active
oldest
votes
21 Answers
21
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.
20
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 meansa
does 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.
20
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 meansa
does 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 Bergantino
375k73486423
375k73486423
20
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 meansa
does not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
add a comment |
20
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 meansa
does not contain any string objects, rather bytes.
– Shiplu Mokaddim
Nov 1 '17 at 18:43
20
20
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))
.
6
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 becausejoin
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 |
@Paolo's s[::-1]
is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s))
.
6
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 becausejoin
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 |
@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
3731519
3731519
answered May 31 '09 at 2:13
Alex Martelli
617k12610331277
617k12610331277
6
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 becausejoin
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 |
6
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 becausejoin
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
6
6
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♦
167k48295247
167k48295247
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 at 17:42
answered Oct 31 '15 at 22:24
dreftymac
15.7k2189153
15.7k2189153
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
pX0r
60369
60369
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])
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])
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 at 22:24
harry
128115
128115
add a comment |
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 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 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
akshaynagpal
1,1081723
1,1081723
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 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 at 15:32
1
1
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 at 15:32
Shouldn't you use xrange since you don't need the list, in python 2?
– UnitasBrooks
May 24 at 15:32
add a comment |
def reverse(input):
return reduce(lambda x,y : y+x, input)
1
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)
1
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.1k116299
37.1k116299
answered Jun 26 '15 at 4:25
Javier
473313
473313
1
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 |
1
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
1
1
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 at 13:57
answered Sep 25 at 11:46
mdn
31339
31339
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
buzhidao
756625
756625
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 at 20:46
answered Apr 16 at 20:38
Nitin Khanna
498312
498312
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 at 11:51
Alex
214
214
add a comment |
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 Creanga
3,69283072
3,69283072
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 at 14:21
matt
385216
385216
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 at 18:23
David the third
1,1641721
1,1641721
add a comment |
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 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 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 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 at 10:03
Kiran Sk
367219
367219
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 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 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 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 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 at 14:58
user128364
899910
899910
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
olga
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,04421425
1,04421425
answered Mar 24 '16 at 18:28
sudistack
8714
8714
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.join
or 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.join
or 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 izquierdo
94
94
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.join
or 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.join
or 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?