Examples of Python adding variables to a string are explained

Source: Internet
Author: User
This article mainly introduced the Python in the string to add the variable instance explanation, has the certain reference value, now shares to everybody, has the need friend to refer to

Sometimes we need to add the appropriate variable to the string, and here are a few ways to add a variable to the string:

1, + hyphen

name = ' Zhangsan ' Print (' My name is ' +name)  #结果为 My name is Zhangsan

2,% characters

name = ' Zhangsan ' age = $ = 4500.225 print (' My name is%s '% (name)) print (' I am%d '% (age) + ' years old ') print (' My PR Ice is%f '% (price)) #保留指定位数小数 (rounded) print (' My price is%.2f '% (price))

Result is

My name is Zhangsan I am years old my price is 4500.225000 my price is 4500.23

3. Format () function

For more variables, adding ' + ' or '% ' is relatively troublesome, in which case the Format function can be used

name = ' Zhangsan ' age = + = 4500.225 info = ' My name is {my_name},i am {my_age} years old,my ' My_price C2/>.format (my_name=name,my_age=age,my_price=price) print (info)

The result is:

My name is zhangsan,i years old,my price is 4500.225

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.