zoukankan      html  css  js  c++  java
  • 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小数

    字符串转义字符: 换行符、\ 反斜杠

    msg = '欢迎'+user+'光临,今天的日期是'+today
    print(msg)  #这种直接拼接的方式不建议实用,因为写代码定义的变量是存在内存里面的,虽然使用简单,但是效率不高。
    msg = '欢迎%s光临,今天的日期是%s
    ' %(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比较合适。

      

  • 相关阅读:
    数组中删除指定某个元素(根据值删除,不是位置)
    gulp使用过程中走过的坑
    H5兼容不同屏幕尺寸
    jQuery基础——事件
    DOM的jquery操作(遍历)
    jquery的DOM操作(创建节点、插入节点、删除节点、复制节点、替换节点、包裹节点)
    gulp插件uncss的使用
    【代码总结-不定期更新】
    【Linux-学习笔记-不定期更新】
    【随时记录的一些东东-不定期更新】
  • 原文地址:https://www.cnblogs.com/Noul/p/9126260.html
Copyright © 2011-2022 走看看