Introduction
Though it might not be a typical factor to do in any real-world state of affairs, reversing strings is a fairly widespread operation you may face in a job interview. Particularly if you’re making use of for a job in a programming language that does not have built-in strategies for reversing strings. By asking you to reverse a string, an interviewer can get a fairly correct impression of the way you strategy analyzing the issue and constructing an answer from scratch.
Additionally, since there may be loads of options for this downside, that is your likelihood to shine and present your consciousness of the totally different execution speeds between totally different algorithms, thus create the very best resolution.
On this article, we’ll check out the way to reverse a string in Python. We’ll contemplate a number of potential options and examine them, so you possibly can select the one that most closely fits your wants.
Clearly, interviews aren’t the one place the place you possibly can face the necessity to reverse a string – for instance, there are some common expression issues which can be solved a lot simpler when working with reversed strings.
Strings in Python
String in Python is an immutable array of bytes – extra particularly a sequence of bytes representing Unicode characters. Truly, a string is written in code as a sequence of characters surrounded by a pair of citation marks (single or double), however they’re internally saved as a sequence of Unicode codes:
example_str = "Howdy World!"
Word: The precise object used to take care of strings in Python known as the str
object. It basically represents a string knowledge kind.
One vital attribute of strings in Python is that they’re immutable, that means that they can not be modified after they had been created. The one solution to modify a string can be to create its modified copy, which complicates many operations on strings. It is no totally different for the one in all our specific curiosity on this article – the operation of reversing a string.
Reversing a String in Python
Now that we have coated all of the fundamentals, we are able to take a look at the way to really reverse a string in Python. As we have acknowledged earlier than, there are a number of methods you are able to do that – on this article, we’ll cowl a few of the most used. Every strategy has its personal strengths and weaknesses, some are extra environment friendly however much less readable. Alternatively, some are actually readable and straightforward to grasp, however at the price of being not that environment friendly.
Within the following sections we’ll be reversing the string "Howdy World!"
, which needs to be reversed to the "!dlroW olleH"
:
example_str = "Howdy World!"
Really helpful Answer: Utilizing the Slice Notation
One other vital property of strings in Python is that they’re sliceable. Which means a substring may be extracted from the unique string – and Python affords a fairly simple method to try this utilizing the slice operator.
The slicing operator in Python has the next syntax – [start:end:step]
. It extracts a substring ranging from the begin
to the finish
. If the step
is a optimistic quantity, the begin
have to be lower than the finish
, subsequently the slicing operator creates a substring shifting forwards. Alternatively, if step
is a destructive quantity, the substring is created going backward within the authentic string. Due to this fact, in the event you set the step
to -1
and depart begin
and finish
clean, you’ll successfully reverse an entire string:
example_str = "Howdy World!"
reversed_str = example_str[::-1]
print(reversed_str)
We have used the slicing operator on our example_str
within the beforehand described method, which is able to yield us the reversed model of our authentic string:
"!dlroW olleH"
This strategy to reversing a string in Python is taken into account to be essentially the most environment friendly for the big enter strings, however that comes at the price of poor readability – particularly for individuals who will not be acquainted with the slicing notation in Python. To enhance that, we are able to wrap the slicing in a perform, which is able to enhance the readability of the ultimate code:
def reverse_string(s):
return s[::-1]
Later, we would use this perform as an alternative of the plain slicing operator to reverse desired string, and the ensuing string would be the similar as earlier than – "!dlroW olleH"
:
reversed_str = reverse_string(example_str)
Recommendation: Wrapping every part of a code in a perform is mostly an excellent follow! Apart from bettering the code readability it really helps you create extra modular and reusable code. Due to this fact, you possibly can wrap every of the next code snippets within the perform in the identical method as proven on this part.
Utilizing be a part of() and reversed()
Though the slicing performs the very best when it comes to pace, the strong different when it comes to readability is to mix two built-in Python strategies – str.be a part of()
and reversed()
.
To begin with, reversed()
returns a reversed iterator for the string handed as its argument. That allows us to go over the unique string backward and append its characters to the empty string utilizing str.be a part of()
perform:
example_str = "Howdy World!"
reversed_str = ''.be a part of(reversed(example_str))
print(reversed_str)
This may create a reversed copy of the unique string:
Take a look at our hands-on, sensible information to studying Git, with best-practices, industry-accepted requirements, and included cheat sheet. Cease Googling Git instructions and really study it!
"!dlroW olleH"
Utilizing a for Loop
Loops can be used to reverse a string in Python – the primary one we’ll contemplate is the for
loop. We will use it to iterate over the unique string each methods – forwards and backward. Since we wish to reverse a string, the very first thing that involves thoughts is to iterate over the string from the top to the beginning and append every character to the brand new string. For that function, we’ll use the reversed()
perform:
example_str = "Howdy World!"
reversed_str = ""
for i in reversed(example_str):
reversed_str += i
print(reversed_str)
We have iterated backward over the unique string and appended every character to the resulting_str
, which is able to retailer the reversed model of the example_str
in the long run:
"!dlroW olleH"
Word: Discover how we have been including every character to the reversed string, however strings in Python are immutable. We will do this as a result of Python, basically, creates a modified copy of a string every time we append a personality to it, earlier than solidifying the end result as an immutable string and returning it.
Another strategy is to iterate over the unique string forwards, from the begin to the top, and create the reversed model of the unique string within the loop itself:
example_str = "Howdy World!"
reversed_str = ""
for i in example_str:
reversed_str = i + reversed_str
print(reversed_str)
This may give us the identical end result as utilizing the reversed iterator within the loop.
Utilizing a whereas Loop
One other loop we are able to use to reverse a string is the whereas
loop. This strategy is a little more sophisticated than others, however can provide you an ideal perception in how reversing string works on a decrease degree:
example_str = "Howdy World!"
reversed_str = ""
i = len(example_str) - 1
whereas i >= 0:
reversed_str += example_str[i]
i -= 1
print(reversed_str)
Which can lead to:
"!dlroW olleH"
Conclusion
As we have seen on this article, there are many approaches on the way to reverse a string in Python, and every of them has its strengths and weaknesses. Usually talking, the a technique you must select for essentially the most time is the slicing operator – it’s the best and essentially the most Pythonic solution to reverse a string. Different approaches are much less environment friendly, subsequently, suppose twice earlier than utilizing them if the execution pace is essential in your code.