Estimated reading time: 2 minutes
Are you building out your program and looking to manipulate strings, specifically reverse them?
Here we are going to go through a number of options, bear in mind there may be more.
The first option is slicing. Essentially with slicing you tell the code where to start splitting out the characters, into their constituent parts.
In the below block:
-1 = start at the end and work backwards
:: = work from the first element to the last element, until no more elements can be chosen.
Putting this together, take joe, and in reverse order print all the characters until you reach the first value.
name = "joe"[::-1] print("By slicing: ", name)
Looping through the values of the string
In the below code, we have a while loop, to achieve the desired effect. The bits to explain in the code are:
strlength = this sets the boundaries of the while loop.
+= This adds whatever variable “strlength” is in the loop to emptylist and saves emptylist for the next iteration until the loop is complete.
str = "joe" emptylist = strlength = len(str) while strlength > 0: emptylist += str[ strlength -1 ] strlength = strlength - 1 print("By using a while loop: ", emptylist)
Using the reverse function
The below takes the string, converts it into a list, and then puts the characters in reverse.
As the characters are in a list, in order to get them back together as a string, we use the “.join” function.
org_string = "joe" createdtemplist = list(org_string) createdtemplist.reverse() string_in_reverse = "".join(createdtemplist) print("By using the reverse function: ", string_in_reverse)
Use list reverse
With list reverse, it is the same as the above approach, except we don’t use .join to get the output back into a string.
This essentially means the final result remains as a list.
string_to_reverse = "joe" string_list = list(string_to_reverse) string_list.reverse() print("By using list reverse: ", string_list)
The output of all this can be seen below:
By slicing: eoj By using a while loop: ['e', 'o', 'j'] By using the reverse function: eoj By using list reverse: ['e', 'o', 'j']