Search results
Results from the WOW.Com Content Network
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.
Literally the first thing? You get the last character of the string, right? So the reverse of a string is the last character, followed by the reverse of everything but the last character, which is where the recursion comes in. The last character of a string can be written as x[-1] while everything but the last character is x[:-1].
3. Less code is usually faster in Python. Luckily, you don't have to guess: python -mtimeit -s"s='x'*100000" "for x in s[::-1]: pass". 100 loops, best of 3: 1.99 msec per loop. python -mtimeit -s"s='x'*100000" "for x in reversed(s): pass". 1000 loops, best of 3: 1.97 msec per loop. python -mtimeit -s"s='x'*100000" "for i in xrange(len(s)-1, 0-1 ...
It's using extended slicing - a string is a sequence in Python, and shares some methods with other sequences (namely lists and tuples). There are three parts to slicing - start, stop and step. All of them have default values - start defaults to 0, stop defaults to len (sequence), and step defaults to 1. By specifying [::-1] you're saying "all ...
For string[0::-1], it's because you tell Python to start at index 0 and go backwards. Of course it doesn't reverse the string. You should do string[len(string)-1::-1] (or surprisingly also string[len(string)::-1]) to get the string reversed like mhlester has said in his answer. – justhalf. Feb 7, 2014 at 1:37.
Method 1: Reverse in place with obj.reverse() If the goal is just to reverse the order of the items in an existing list, without looping over them or getting a copy to work with, use the <list>.reverse()function. Run this directly on a list object, and the order of all items will be reversed:
To reverse the list you can use reverse(), which reverses the list in place or the slicing syntax [::-1] which returns a new, reversed list. Share Improve this answer
1. To reverse an array from a particular index to another, please use this: #start is the starting index. #end is the ending index. while start<end: nums[start],nums[end] = nums[end],nums[start] start+=1. end-=1. All this does is that it picks one element from the start and one from the end and swaps them.
I want to do a string replace in Python, but only do the first instance going from right to left. In an ideal world I'd have: myStr = "mississippi" print myStr.rreplace("iss","XXX",1) > missXXXippi
1. I think this answer is wrong. It gives the index of the first 'I', not what the OP wanted. To find the 2nd 'I', s.find ('I', s.find ('I')+1) returns 16. To find the last 'I', s.rfind ('I') would work. To find the indeces of all 'I' occurrences: locs = [idx for idx,ltr in enumerate (s) if ltr == 'I'] – John.