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