python-字符串格式化
一、导入模块
导入模块使用import,例:import datetime ,即导入datetime模块
datetime.datetime.today() 获取到今天的日期
import datetime user = 'yanhx' today = datetime.datetime.today() #获取到今天的日期 print(type(user)) # <class 'str'> print(type(today)) # <class 'datetime.datetime'> today = str(today) print(today) # 2019-01-31 16:06:34.236825 print(type(today)) # <class 'str'>
二、占位符及字符串转义字符
占位符: %s 字符串;%d 整数; %f小数
字符串转义字符:\n 换行符、\\ 反斜杠
msg = '欢迎'+user+'光临,今天的日期是'+today print(msg) #这种直接拼接的方式不建议实用,因为写代码定义的变量是存在内存里面的,虽然使用简单,但是效率不高。 msg = '欢迎%s光临,今天的日期是%s\n' %(user,today) print(msg)
三、字符串格式化示例
round()代表保留几位小数
age = 18 score = 98.758 # float类型 round(score,2)# round代表保留几位小数 print(round(score,2)) # 输出:98.76 msg = '你的年龄是%d,你的分数是%f'%(age,score) print(msg) # 输出:你的年龄是18,你的分数是98.758000
%.2f保留两位小数
age = 18 score = 98.758 # float类型 round(score,2)# round代表保留几位小数 print(round(score,2)) # 输出:98.76 msg = '你的年龄是%d,你的分数是%.2f'%(age,score)#%.2f保留两位小数 print(msg) # 输出:你的年龄是18,你的分数是98.76
四、大括号的方式
name = 'lily' phone = '1381232523' grade = 'tmz' money = 5000 score = 98.133 addr = "北京" name2='李韩韩' sql = 'insert into students values ("%s","%s","%s"' \ ',"%d","%.2f","%s");' % (phone,name,grade,money,score,addr) welcome = '{name},欢迎登陆,今天的日期是{today}'.format(today=today,name=name2 ) welcome2 = '{},欢迎登陆,今天的日期是{}'.format(today,name) print(welcome) print(welcome2)
参数较多的时候使用format比较合适。