Home > Backend Development > Python Tutorial > Example explanation of adding variables to strings in Python

Example explanation of adding variables to strings in Python

不言
Release: 2018-05-02 11:13:17
Original
2444 people have browsed it

This article mainly introduces examples of adding variables to strings in Python. It has certain reference value. Now I share it with you. Friends in need can refer to it

Sometimes, we need Add corresponding variables to the string. Here are several methods for adding variables to the string:

1. Hyphen

name = 'zhangsan' 
print('my name is '+name) 
 
#结果为 my name is zhangsan
Copy after login

2, % character

##

name = 'zhangsan' 
age = 25 
price = 4500.225 
print('my name is %s'%(name)) 
print('i am %d'%(age)+' years old') 
print('my price is %f'%(price)) 
#保留指定位数小数(四舍五入) 
print('my price is %.2f'%(price))
Copy after login

The result is

my name is zhangsan 
i am 25 years old 
my price is 4500.225000 
my price is 4500.23
Copy after login

3. format() function

for variables In many cases, it is relatively troublesome to add ' ' or '%'. In this case, you can use the format function

name = 'zhangsan' 
age = 25 
price = 4500.225 
info = 'my name is {my_name},i am {my_age} years old,my price is {my_price}'\ 
 .format(my_name=name,my_age=age,my_price=price) 
print(info)
Copy after login

The result is:

my name is zhangsan,i am 25 years old,my price is 4500.225
Copy after login

Related recommendations:


Python find the position of a character in a string example

The above is the detailed content of Example explanation of adding variables to strings in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template