python 中字符串中含变量处理方法

1. 简单粗鲁的字符串拼接

name = "abc"
age = 25
info = "the name is "+name +"\nthe age is " + str(age)
print(info)

2使用百分号%

name = "abc"
age = 25
info = "the name is %s \nthe age is %s"%(name ,age)
print(info)

3.使用format

name = "abc"
age = 25
info_1 = "the name is {name_} \nthe age is {age_}".format(name_=name ,age_= age)
print(info_1)
info_2 = "the name is {0} \nthe age is {1}".format(name ,age)
print(info_2)
info_3 = "the name is {} \nthe age is {}".format(name ,age)
print(info_3)

4使用f、大括号{}

name = "abc"
age = 25

info = f"the name is {name} \nthe age is {age}"
print(info)

 

输出的内容都是一样的:
the name is abc
the age is 25

  

posted @ 2021-07-07 11:19  tochenwei  阅读(341)  评论(0编辑  收藏  举报