Python基础之字符串拼接简单介绍

时间:2023-03-09 01:54:56
Python基础之字符串拼接简单介绍

字符串拼接:

%s表示可以传任意类型的值,%d表示只能传数字

test = "my name is %s,age %d" %("xyp",19)
print(test) 

结果:

Python基础之字符串拼接简单介绍

或者:

test = "my name is %(name)s,age %(age)d" %{'name':'xyy','age':19}
print(test) // 这种方式传的值只能是字典

结果:

Python基础之字符串拼接简单介绍

%f后面接的是浮点数(小数)默认小数点后面是六位数,不够的用0补

test = "num is %f" %99.97682
print(test)

结果:

Python基础之字符串拼接简单介绍

%.2f表示小数点后面的数保留两位并会自动进行四舍五入,可以是.3.4.5

test = "num is %.2f" %99.97682
print(test) 

结果:

Python基础之字符串拼接简单介绍

或者:

test = "num is %(num).2f" %{'num':99.97682}
print(test)

结果:

Python基础之字符串拼接简单介绍

%%表示在数字后面加上一个%号

test = "percent is %.2f%%" %99.97682
print(test) 

结果:

Python基础之字符串拼接简单介绍