Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the inverted string reversed () and slice in Python

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to analyze the inverted string reversed () and slices in Python. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

When we often use Python strings in our code, you may need to use them in reverse order. Python includes handy tools and techniques that can help you in these situations. Using them, you will be able to quickly and efficiently build a reverse copy of an existing string.

Understanding these tools and techniques for reversing strings in Python will help you improve your proficiency as a Python developer.

Use the core Python tool to reverse the string

In some specific cases, you may need to use Python strings in reverse order. For example, suppose you have a string and want a quick way to reverse it to get it. What Python tools can you use to help? "ABCDEF"FEDCBA"

Strings are immutable in Python, so it is not possible to reverse a given string in place. You need to create a reverse copy of the target string to meet the requirements.

Python provides two direct ways to reverse strings. Because strings are sequences, they are indexable, sliceable, and iterable. These features allow you to use slices to directly generate a copy of a given string in reverse order. The second option is to use the built-in function reversed () to create an iterator that generates the characters of the input string in reverse order.

Second, reverse the string by slicing

Slicing is a useful technique that allows you to extract items from a given sequence using different combinations of integer indexes called offsets. When it comes to slicing strings, these offsets define the index of the first character in the slice, the index of the character that stops the slice, and a value that defines how many characters to skip per iteration.

To slice a string, you can use the following syntax:

A_ string[start: stop:step]

Your offset start,stop and step. This expression extracts all characters step from startto stop − 1by. You'll learn more about what all this means later.

All offsets are optional and have the following default values:

Here, start represents the index of the first character stop in the slice, while saving the index that stops the slicing operation. The third offset, step, allows you to determine how many characters the slice will skip in each iteration.

Note: the slicing operation completes the stop when an index equal to or greater than is reached. This means that it will never include the item at that index (if any) in the final slice.

This step offset allows you to fine-tune how to skip other characters you need to extract from the string:

> letters = "AaBbCcDd" > > # Get all characters relying on default offsets > letters [::] 'AaBbCcDd' > letters [:]' AaBbCcDd' > # Get every other character from 0 to the end > letters [:: 2] 'ABCD' > # Get every other character from 1 to the end > letters [1:: 2]' abcd'

Here, you first slice without an explicit offset value provided by letters to get a complete copy of the original string. To do this, you can also use slices that omit the second colon (:). As step equals 2, the slice starts from every other character in the target string. You can use different offsets to better understand how slices work.

Why are slices and the third offset related to string inversion in Python? The answer lies in how step handles negative values. If you provide a negative value of step, the slice runs backwards, from right to left.

For example, if you set it to stepequal-1, you can build a slice that retrieves all characters in reverse order:

> letters = "ABCDEF" > letters [::-1] 'FEDCBA' > letters'ABCDEF'

This slice returns all characters 0 from the right end of the string (index equals) to the left end of the len (letters)-1 string (index is). When you use this technique, you get a copy of the original string in reverse order without affecting the original content letters.

Another technique for creating a reverse copy of an existing string is to use slice (). The signature of this built-in function is as follows:

Slice (start, stop, step)

This function takes three arguments, which have the same meaning as the offset in the slicing operator, and returns a slicing object indicating the call to range (start, stop, step).

We can use slice () to simulate the slice [::-1] and quickly reverse the string. Continue and slice () run the following call in square brackets:

> letters = "ABCDEF" > > letters [slice (None, None,-1)] 'FEDCBA'

The first two arguments slice () passed in by None tell the function that you want to rely on its internal default behavior, which is the same stop as a standard slice without start and values. In other words, passing None to start and stop means that you need to slice from the left end of the underlying sequence to the right end.

Third, use .join () and reverse the string reversed ()

The second, arguably the most Pythonic way to reverse a string, is reversed () and str.join (). If you pass the string to reversed (), you get an iterator that generates characters in reverse order:

> greeting = reversed ("Hello, World!") > next (greeting)'! > > next (greeting)'d' > next (greeting)'l'

When you call next () withgreeting as a parameter, you get each character from the right end of the original string.

An important point to note reversed () is that the generated iterator generates characters directly from the original string. In other words, it does not create a new reverse string, but reads characters backwards from an existing string. This behavior is quite effective in terms of memory consumption and can be a fundamental victory in some contexts and situations, such as iterations.

We can use reversed () to call the obtained iterator directly as a parameter .join ():

> ".join (reversed (" Hello, World! "))'! dlroW, olleH'

In this single-line expression, you pass the result of the call, reversed (), directly as an argument to .join (). Therefore, you will get a reverse copy of the original input string. The combination of reversed () and. Join () is a good choice for reversing strings.

Fourth, generate the inversion string manually

So far, you have learned about the core Python tools and techniques for quickly inverting strings. Most of the time, they will be your best choice. However, you may need to manually reverse the string at some point in the coding adventure.

In this section, you will learn how to reverse strings using explicit loops and recursion. The last technique uses functional programming with the help of the Pythonreduce () function.

Fifth, reverse the string in the loop

The first technique you'll use to reverse strings involves for loops and concatenation operators (+). Using two strings as operands, this operator returns a new string concatenating the original string. The whole operation is called concatenation.

Note: using .join () is the recommended way to concatenate strings in Python. It is clean, efficient and Pythonic.

This is a function that takes a string and reverses it in a loop using concatenation:

> def reversed_string (text):... Result = ""... For char in text:... Result = char + result... Return result... > reversed_string ("Hello, World!")'! dlroW, olleH'

In each iteration, the loop takes the subsequent characters char, fromtext and concatenates it with the current content of result. Note that result initially saved an empty string (""). Then reassign the new intermediate string to result. At the end of the loop, result saves a new string as a reverse copy of the original string.

Note: because Python strings are immutable data types, you should keep in mind that the examples in this section use a wasteful technique. They rely on creating consecutive intermediate strings just to discard them in the next iteration.

If you prefer to use whileloop, you can do the following to build a reverse copy of a given string:

> def reversed_string (text):... Result = ""... Index = len (text)-1... While index > = 0 VRO... Result + = text [index]. Index-= 1... Return result... > reversed_string ("Hello, World!")'! dlroW, olleH'

Here, you first use len (), which calculates the last character in the index input string. The loop goes down from index to and includes 0. In each iteration, you use the extended assignment operator (+ =) to create an intermediate string that concatenates the content result with the corresponding character from text. Again, the end result is a new string produced by reversing the input string.

Sixth, reverse the string with recursion

We can also use recursion to reverse the string. Recursion means that a function calls itself in its own body. To prevent infinite recursion, you should provide a basic situation in which results can be generated without having to call the function again. The second component is the recursive case, which starts the recursive loop and performs most of the calculations.

Here is how to define a recursive function that returns an inverse copy of a given string:

> def reversed_string (text):... If len (text) = = 1RV... Return text... Return reversed_string (text [1:]) + text [: 1]... > > reversed_string ("Hello, World!")'! dlroW, olleH'

In this case, you first check the basics. If the input string has only one character, the string is returned to the caller.

The last statement, the recursive case, calls reversed_string () itself. This call takes a slice of the text [1:] input string as a parameter. This slice contains all the characters in the text except the first. The next step is to add the result of the recursive call to the text of the first character string contained in text [: 1].

An important thing to note in the above example is that if you pass a long string as an argument to reversed_string (), you will get a RecursionError:

> very_long_greeting = "Hello, World!" * 1000> reversed_string (very_long_greeting) Traceback (most recent call last):... RecursionError: maximum recursion depth exceeded while calling a Python object

Reaching the default recursion limit of Python is an important issue that you should consider in your code. However, if you do need to use recursion, you can still choose to set recursive limits manually.

You can check the recursive limit sys of the current Python interpreter by calling getrecursionlimit () from. By default, this value is usually 1000. You can use setrecursionlimit () sys from the same module. Using these functions, you can configure the Python environment so that your recursive solution works. Let's try it!

Use reduce () to reverse the string

If you prefer functional programming, you can use reduce () fromfunctools to reverse the string. Pythonreduce () takes a collapse or reduction function and an iterable object as parameters. It then applies the provided function to the project in the input iteration and returns a single cumulative value.

Here's how you can reverse a string with reduce ():

> from functools import reduce > > def reversed_string (text):... Return reduce (lambda a, b: B + a, text)... > reversed_string ("Hello, World!")'! dlroW, olleH'

In this example, the lambda function takes two strings and concatenates them in reverse order. Call reduce () to apply lambdatotext in the loop and build a reverse copy of the original string.

Reverse traversing the string

Sometimes you may want to traverse existing strings in reverse order, a technique often referred to as reverse iteration. Depending on your specific needs, you can reverse iterate over the string using one of the following options:

The built-in function of the reversed ()

Slice operator, [::-1]

Reverse iteration is arguably the most common use case for these tools, so in the following sections, you will learn how to use them in the context of iteration.

8. The built-in function of reversed ()

The most readable and Pythonic way to iterate over strings in reverse order is to use reversed (). Not long ago, you knew about this function when you used it with .join () to create a reverse string.

However, the main intention and use case reversed () is to support reverse iterations of Python iterable objects. Taking a string as an argument, reversed () returns an iterator that generates characters from the input string in reverse order.

Here is how to iterate over the string reversed () in reverse order:

> greeting = "Hello, World!" > > for char in reversed (greeting):. Print (char).! dlroW,olleH > > reversed (greeting)

For the loop in this example is very readable. The name reversed () clearly expresses its intention and conveys that the function does not have any side effects on the input data. Because reversed () returns an iterator, the loop is also efficient in terms of memory usage.

IX. Slice operator, [::-1]

The second way to reverse iterate a string is to use the extended slicing syntax you saw earlier in the a_string [::-1] example. Even if this approach is not good for memory efficiency and readability, it still provides a way to quickly iterate over reverse copies of existing strings:

> greeting = "Hello, World!" > > for char in greeting [::-1]:. Print (char)...! dlroW,olleH > > greeting [::-1]'! dlroW,olleH'

In this case, we apply the slice operator greeting to create a reverse copy of it. Then you use that new reverse string to feed the loop. In this case, you are iterating over a new reverse string, so the solution is less memory efficient than using reversed ().

Create a custom reversible string

If you've ever tried to reverse the Python list, you know that there is a convenient way for lists to be called in-situ. Reverse () to reverse the underlying list. Because strings are immutable in Python, they do not provide similar methods.

However, you can still use .reverse () to mimic list.reverse (). You can do this:

> from collections import UserString > > class ReversibleString (UserString):... Def reverse (self):... Self.data = self.data [::-1]...

ReversibleString inherits from UserString, which is a class of the collections module. UserString is a wrapper for str built-in data types. It is designed to create str. UserString is handy when you need to create custom string classes with additional functionality.

UserString provides the same functionality as regular strings. It also adds a public property called .data holding and allows you to access the wrapped string object.

Inside ReversibleString, you create .reverse (). This method reverses the wrapped string .data and reassigns the result back to .data. From the outside, the work of calling .reverse () is like reversing a string into place. However, what it actually does is create a new string that contains the original data in reverse order.

Here is how ReversibleString works in practice:

> text = ReversibleString ("Hello, World!") > text'Hello, Worldworkers'> # Reverse the string in place > text.reverse () > textroomroomdlroW, olleH'

When you call .reverse () on, the method is text as if you were making in-place changes to the underlying string. However, you are actually creating a new string and assigning it back to the wrapped string. Notice that text now saves the original strings in reverse order.

Because UserString provides the same functional str as its superclass, you can reversed () to perform reverse iterations out of the box:

> text = ReversibleString ("Hello, World!") > > # Support reverse iteration out of the box > for char in reversed (text):. Print (char).! dlroW,olleH > > text "Hello, World!"

Here, you call reversed () withtext as an argument to provide the for loop. This call works as expected and returns the corresponding iterator, because UserString originates from str. Note that the call to reversed () does not affect the original string.

11. Sort Python strings in reverse order

The last topic we will learn is how to sort the characters of a string in reverse order. This is convenient when you do not process strings in a specific order and need to sort them in reverse alphabetical order.

To solve this problem, you can use sorted (). This built-in function returns a list of all items that can be iterated in. In addition to input iterability, sorted () also accepts the reverse keyword parameter. True if you want to enter iterable objects to sort in descending order, you can set this parameter to:

> vowels = "eauoi" > # Sort in ascending order > sorted (vowels) ['asituation,' estrangement, 'iTunes,' oasis,'u'] > # Sort in descending order > sorted (vowels, reverse=True) ['upright,' oval, 'iTunes,' eBay,'a']

When you call sorted () with a string as an argument and reverse is set to True, you get a list of input string characters in reverse or descending order. Because sorted () returns a list object, you need a way to convert the list back to a string.

Similarly, we can use .join () as in the previous section:

> vowels = "eauoi" > > ".join (sorted (vowels, reverse=True)) 'uoiea'

In this code snippet, you call .join () with an empty string that acts as a delimiter. The parameter to.join () is the result True that calls sorted () withvowels as a parameter and reverse is set to.

You can also use sorted () to iterate through strings in sort and reverse order:

> for vowel in sorted (vowels, reverse=True):... Print (vowel). Uoiea

The statement sorted () given by the reverse allows you to sort the iterables, including strings, in descending order. So if you need string characters sorted in reverse alphabetical order, sorted () suits you.

Conclusion:

Reversing and processing strings in reverse order can be a common task in programming. Python provides a set of tools and techniques to help you perform string inversion quickly and efficiently. In this tutorial, you learned about these tools and techniques and how to take advantage of them in string processing challenges.

Summary:

Quickly build reverse strings by slicing

Use reversed () and create a reverse copy of the existing string. Join ()

Manually create reverse strings using iterations and recursion

Loop through strings in reverse order

Sort strings using descending order sorted ()

Although this topic itself may not have many exciting use cases, knowing how to reverse strings is useful for coded interviews for entry-level positions. You'll also find that mastering different ways to reverse strings can help you truly conceptualize the invariance of strings in Python a remarkable feature of the language.

The above is how to analyze the inverted string reversed () and slices in Python. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report