当前位置: 首页 > news >正文

Python 关于字符串格式化

在Python中,字符串格式化有以下几种方法:

1.可以使用字符串的str.center(width), str.ljust(width), 和 str.rjust(width)方法来实现字符串的居中、左对齐和右对齐操作。

  1. 居中对齐:

    text = "Python"
    centered_text = text.center(10)  # 在宽度为10的空间中居中对齐
    print(centered_text)  # 输出结果为 "  Python  "
    
  2. 左对齐:

    text = "Python"
    left_aligned_text = text.ljust(10)  # 在宽度为10的空间中左对齐
    print(left_aligned_text)  # 输出结果为 "Python    "
    
  3. 右对齐:

    text = "Python"
    right_aligned_text = text.rjust(10)  # 在宽度为10的空间中右对齐
    print(right_aligned_text)  # 输出结果为 "    Python"
    

2.使用百分号(%)进行格式化:

name = "Alice"
age = 30
formatted_string = "Name: %s, Age: %d" % (name, age)
print(formatted_string)

3.使用str.format()方法进行格式化:

name = "Bob"
age = 25
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)

4.使用模板字符串Template:

from string import Template
name = "David"
age = 40
template = Template("Name: $name, Age: $age")
formatted_string = template.substitute(name=name, age=age)
print(formatted_string)

5.使用f-strings(在Python 3.6及更高版本中可用):

name = "Charlie"
age = 35
formatted_string = f"Name: {name}, Age: {age}"
print(formatted_string)

如果需要进一步控制格式化语法中变量的形式,可以参照下面表格来进行字符串格式化操作:

请添加图片描述

如:

name = "Alice"
age = 30
height = 1.652

# 控制小数点后的位数
print("Height: %.2f" % height)  # 输出结果为 "Height: 1.65"

# 控制字符串的长度
print("Name: %10s" % name)  # 输出结果为 "Name:      Alice"
print("Name: %-10s" % name)  # 输出结果为 "Name: Alice     "

# 使用 f-string 格式化字符串
formatted_string = f"Name: {name}, Age: {age}, Height: {height:.2f}"
print(formatted_string)
# 输出结果为“ Name: Alice, Age: 30, Height: 1.65”

相关文章:

  • 【Linux】将U盘中的程序更新到开发板中 shell 脚本
  • VRTK4教程 一:资源导入、Unity设置、连接头盔
  • SO3控制器原理与实现(对飞行器的控制实践)
  • 算法(十一)贪婪算法
  • 9秒爬取庆余年2分集剧情
  • 牛客小白月赛95 (个人题解)(待完成)
  • UDP通信
  • Elasticsearch 认证模拟题 - 5
  • 结构体相关习题的补充
  • 从0开始学统计-什么是回归?
  • Nuxt.js静态生成与动态路由策略
  • 【论文解读】Performance of AV1 Real-Time Mode
  • 基于java的CRM客户关系管理系统(一)
  • Tomcat
  • 21.Redis之分布式锁
  • mongodb数据库查询调优之explain方法详解
  • 数据结构的希尔排序(c语言版)
  • 【iOS】didReceiveMemoryWarning实例方法
  • 计算机网络基础知识(持续更新中)
  • 【计算机网络】——物理层(图文并茂)
  • 汇源果汁发文:经营情况一切正常
  • 上海“量子城市”先导应用场景落地曹杨社区,提供哪些服务?
  • 中国社科院:网文市场超430亿元,作者破3000万人
  • 习近平圆满结束对俄罗斯国事访问并出席纪念苏联伟大卫国战争胜利80周年庆典
  • 胖东来发布和田玉、翡翠退货说明:不扣手续费等任何费用
  • 98岁动物学家、北京大学教授杨安峰逝世