栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python -- 字符串格式化

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python -- 字符串格式化

https://zhuanlan.zhihu.com/p/90439125
https://blog.csdn.net/sunxb10/article/details/81036693

%
# 使用元组
name = "Eric"
age = 3
print("Hello, %s. You are %s." % (name, age))

# Hello Eric. You are 3.
format()
  • 设置指定位置
print("{1} {0} {1}".format("hello", "world"))  # 设置指定位置

# world hello world
  • 设置参数
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 参数获取方式:直接指定;字典;列表
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
 
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
 
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的

# 网站名:菜鸟教程, 地址 www.runoob.com
f-strings

注意:该函数仅适用于3.6及以上版本

  • 时间
import datetime
e = datetime.datetime.today()
print(f'the time is {e:%Y-%m-%d (%a) %H:%M:%S}')   # datetime时间格式

# the time is 2021-10-08 (Fri) 11:38:52
  • 保留小数
d = 0.5 + 2.5j
print(f'd is {d:30.3e}')      # 宽度30位,科学计数法,3位小数
# d is           5.000e-01+2.500e+00j
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/304279.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号