温馨提示×

python print format函数的字符串操作技巧有哪些

小樊
83
2024-08-10 01:45:39
栏目: 编程语言

  1. 使用占位符:在字符串中使用占位符({})表示要替换的位置,然后使用format函数传入要替换的值。

例如:print(“Hello, {}”.format(“World”))

  1. 指定位置替换:可以在占位符中指定要替换的位置。

例如:print(“{1}, {0}”.format(“World”, “Hello”))

  1. 格式化输出数字:可以使用格式化字符串来控制数字的输出格式。

例如:print(“The result is {:.2f}”.format(3.14159))

  1. 格式化日期时间:可以使用格式化字符串来控制日期时间的输出格式。

例如:print(“Today is {:%Y-%m-%d}”.format(datetime.datetime.now()))

  1. 对齐文本:可以使用格式化字符串来对齐文本的输出。

例如:print(“{:<10} {:>10}”.format(“left”, “right”))

  1. 格式化字典:可以使用格式化字符串来输出字典的内容。

例如:info = {“name”: “Alice”, “age”: 30} print(“Name: {name}, Age: {age}”.format(**info))

0