Format the python string and format the python string.

Source: Internet
Author: User

Format the python string and format the python string.

Most of the time, when printing input content, we want a simple format instead of splicing.

General Practice:

1 name = input("name:").strip()2 age = input("age:").strip()3 job = input("job:").strip()4 print("Name:" + name + " Age:" + age + " Job:" + job)

Result:

Name:zhang Age:24 Job:IT

Format the output:

Name = input ("name :"). strip () age = input ("age :"). strip () job = input ("job :"). strip () info = ''' ---------- info of % s ------- # Every % s in info is a placeholder Name: % sAge: % sJog: % s ---------- end --------------- ''' % (name, name, age, job) # % of this line is to associate the placeholder with the variable following the brackets with print (info)

Result:

----------info of zhang -------Name :  zhangAge :   24Jog :   IT----------end---------------

In addition to % s, there are % d. % d indicates that you can only enter numbers. We will change % s of age to % d to see what will happen.

 1 name = input("name:").strip() 2 age = input("age:").strip() 3 job = input("job:").strip() 4 info = ''' 5 ----------info of %s ------- 6 Name :  %s 7 Age :   %d 8 Jog :   %s 9 ----------end---------------10 '''%(name, name, age, job)11 print(info)

Error message:

Traceback (most recent call last):  File "C:/Users/admin/PycharmProjects/test.py", line 10, in <module>    '''%(name, name, age, job)TypeError: %d format: a number is required, not strName:li Age:25 Job:farmer

The reason is that the input is a number but saved to the variable as a string 'str' type. To use % d, you must modify the variable type, you can change the age variable of row 10th to the int type as follows to run the command normally.

'''%(name, name, int(age), job)

Therefore, in formatting output, % s is more omnipotent, Because you input a string 'str', so no error is reported.

 

Related Article

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.