Python Learning Notes (11th lesson)

Source: Internet
Author: User

This section learns about Python's formatted output, file manipulation, and the simple use of JSON

1. Formatted output

To convert a non-string type to a string, you can use the function: str () or repr (), (the difference between these two functions I still do not understand, ask for answers )

>>> STR ([1,2,3,4])'[1, 2, 3, 4]'>>> repr ([1,2,3,4]) ' [1, 2, 3, 4] '>>> str ' >>>repr (Ten)'  ten'

You can use Str.ljust (), Str.rjust (), Str.center () to set the alignment of a string

 for  in range (1,11):    Print str (x). Ljust (2), str (x*x). Ljust (3), str (x*x*x). Ljust (4)     1  1   1   2  4   8   3  9   +  4  +  5  6  216 7  343 8  9  bayi  729 10 100 1000

We can also use Str.format () to set the alignment of the string ({} fill ^, <, > center, Align Left, align Right ):

 for  in range (1,11):    print"{0:<2d} {1:<3d} {2:<4d}" . Format (x,x*x,x*x*x)    1  1   1   2  4   8   3  9  4 16  5  6  216 7  343 8 +  9  bayi  729 10 100 1000

Other ways to use Str.format ():

>>> print "His name was {},his age is {}". Format (' Jack ', 30)
His name is Jack,his 30
>>> print "His name was {1},his age is {0}". Format (' Jack ')
His name is Jack,his 30
>>> print "His name was {Name},his age was {age}". Format (age=30,name= ' Jack ')
His name is Jack,his 30
>>> print "PI is {0:.2f}". Format (3.1415926)
Pi is 3.14
>>> t={' name ': ' Jack ', ' Age ': 30}
>>> print "His name was {0[name]:s},his age is {0[age]:d}". Format (t)
His name is Jack,his 30
>>> print "His name was {Name:s},his age is {age:d}". Format (**t)
His name is Jack,his 30

We also have a format for the output form, as follows:

Print " Pi is%.2f " % (3.1415926 is 3.14

Python Learning Notes (11th lesson)

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.