"Python CookBook2" chapter I text-Test whether an object is a class string && string alignment

Source: Internet
Author: User

tests whether an object is a class string

Task

Sometimes it is necessary to test an object, especially if you are writing a function or method, you often need to test whether the passed argument is a string.

Solution Solutions

Use the built-in isinstance and basestring to quickly and easily query whether an object is a string or a Unicode object method, as follows:
Code:

def isastring (AAA):     return isinstance (aaa,basestring)

Operation Result:

>>> isastring ('aaa') True

string Alignment

Task

Implement string alignment: Left-justified, centered, right-aligned

Solution Solutions

This is the problem that the Ljust, Rjust, and center methods of the string object solve. Each method requires a parameter that indicates the width of the resulting string, and then returns a copy of the string with spaces added to the left, right, or both ends:

>>>Print "python". Ljust (15,"+") Python+++++++++>>>Print "python". Rjust (15,"+")+++++++++python>>>Print "python". Center (15,"+")+++++python++++

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.