Python string sorting method _python

Source: Internet
Author: User

In this paper, the method of implementing string ordering by Python is briefly described, which is a very practical technique in Python programming. Share for everyone to use for reference. The specific methods are as follows:

In general, it's 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 to be sorted in the 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 methods are as follows:

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

Programmers who have just turned from C + + and other languages tend to feel very accustomed to it, because in C + + These are a line of things can be done. Therefore, a simple string sorting method is given here.

The implementation code is as follows:

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

Because of the use of a lambda, a little difficult to understand, but the idea is good.

I hope this article will help you with your 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.