00309 Python str.format


前言

Python nonlocal关键字。

Operating System: Ubuntu 22.04.4 LTS

参考文档

介绍

在Python中,str.format() 方法是一种格式化字符串的强大方式。它允许你通过在字符串中使用花括号 {} 作为占位符,来插入变量、表达式或字面值。以下是 str.format() 方法的一些基本用法:

基本用法

name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))

输出:

My name is Alice and I am 30 years old.

按索引格式化

print("My name is {0} and I am {1} years old. {0}'s age is {1}.".format(name, age))

输出:

My name is Alice and I am 30 years old. Alice's age is 30.

按关键字格式化

print("My name is {name} and I am {age} years old.".format(name="Bob", age=25))

输出:

My name is Bob and I am 25 years old.

格式化数字

number = 3.14159
print("The number pi is {:.2f}".format(number))

输出:

The number pi is 3.14

填充和对齐

print("{:<10}".format("left"))    # 左对齐
print("{:>10}".format("right"))   # 右对齐
print("{:^10}".format("center"))  # 居中对齐

输出:

left      
       right
   center  

进制转换

number = 255
print("Binary: {0:b}, Hex: {0:x}, Octal: {0:o}".format(number))

输出:

Binary: 11111111, Hex: ff, Octal: 377

使用 **kwargs

def greet(first_name, last_name):
    return "Hello, {first_name} {last_name}".format(**locals())

print(greet("Alice", "Smith"))

输出:

Hello, Alice Smith

str.format() 方法非常灵活,支持多种格式化选项,你可以根据需要定制字符串的输出格式。

结语

第三百零九篇博文写完,开心!!!!

今天,也是充满希望的一天。


文章作者: LuYF-Lemon-love
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 LuYF-Lemon-love !
  目录