字符串格式化

字符串拼接有3种方法

 

  • 第一种就是用+号拼接
1 import datetime
2 #字符串格式化
3 today =str(datetime.datetime.today())
4 name = 'zjr'
5 #直接拼接
6 print(name+',欢迎登陆,今天的日期是'+today)#内存存了3个,效率低

    缺点:内存地址占用多;‘’欢迎登陆,今天的日期是'占用一块内存,today占用一块内存,连一起的长字符串再占用一个内存;

 

  • 第二种是%s、%d、%f占位
 1 import datetime
 2 #字符串格式化
 3 today =str(datetime.datetime.today())
 4 name = 'zjr'
 7 #占位符 %s %d %f
 8 welcome = '%s,欢迎登陆,今天的日期是%s'%(name,today)
 9 print(welcome)
10 age = 18
11 age_str = '你的年龄是%d'%age
12 print(age_str)
13 score = 87.555454
14 score_str = '你的成绩是%f'%score
15 score_str1 = '你的成绩是%.2f'%score#保留2位小数
16 print(score_str)
17 print(score_str1)

       有多少个占位符,后面就得跟多少值,否则会报错!

 

  • 第三种是format
import datetime
#字符串格式化
today =str(datetime.datetime.today())
name = 'zjr'#format 参数多时,可以一一对应
welcome = '{},欢迎登陆,今天的日期是{}'.format(name,today)
welcome2 = '{myname},欢迎登陆,今天的日期是{date}'.format(myname=name,date=today)
print(welcome)
print(welcome2)

  参数多时建议用format方式,才不会乱!{}中间不写变量名和%s是一样的使用。

  •  format_map 传入字典
    print('{name},{value}'.format_map({"name":"zjr","value":"haha"}))#格式化入参传字典

     

posted @ 2020-08-14 20:25  Mezhou  阅读(114)  评论(0编辑  收藏  举报