Python string Sorting method

Source: Internet
Author: User
In this paper, we briefly summarize the method of Python's implementation of string ordering, which is a very practical technique in Python program design. Share it for everyone's reference. Here's how:

In general, it is quite troublesome to sort a string in Python:

One, the string type in Python is not allowed to change elements directly. You must first place the string you want to sort in a container, such as list.

Second, the sort () function of the list container in Python does not return a value.

So it often takes several lines of code to sort strings in Python.

The implementation method is as follows:

>>> s = "string" >>> L = List (s) >>> L.sort () >>> s = "". Join (L) >>> s ' Ginrst '

Programmers who have just been transferred from languages such as C + + will often feel very accustomed to it, because in C/s + + These are all things that can be done with a single line of statements. Therefore, here is a simple method for sorting strings.

The implementation code is as follows:

>>> s = "string" >>> s = "". Join ((Lambda x: (X.sort (), x) [1]) (list (s))) >>> s ' Ginrst '

It's a little bit hard to understand because of the lambda, but it's better to get it figured out.

Hopefully this article will help you with Python programming.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.