Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

Python .format使用

  1. User

    Python .format使用

  2. Assistant

    在Python中,.format()用于格式化字符串。它是一种灵活的方法,可以根据需要动态的插入值到字符串中。以下是.format()的一些常见用法:

    1. 位置参数: 在字符串中使用花括号{}来指示要插入的位置,然后通过.format()方法传递相应的参数值。

      示例:

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

      输出:

      My name is Alice, and I am 25 years old.
      
    2. 关键字参数: 在字符串中使用花括号{}指定参数的字段名,然后通过关键字参数的方式传递参数值给.format()方法。

      示例:

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

      输出:

      My name is Alice, and I am 25 years old.
      
    3. 位置与关键字混合使用: 可以混合使用位置参数与关键字参数,但是位置参数必须在关键字参数之前。

      示例:

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

      输出:

      My name is Alice, and I am 25 years old.
      
    4. 格式控制: 在花括号中可以使用冒号来指定对参数的格式控制。常见的控制项包括宽度、精度、进制等。

      示例:

      num = 3.1415926
      print("The value of pi is {:.2f}".format(num))
      

      输出:

      The value of pi is 3.14
      
    5. 对象属性: 如果参数是某个对象的属性,可以使用点.来访问属性。

      示例:

      class Person:
        def __init__(self, name, age):
          self.name = name
          self.age = age
      
      person = Person("Alice", 25)
      print("My name is {person.name}, and I am {person.age} years old.".format(person=person))
      

      输出:

      My name is Alice, and I am 25 years old.
      

    以上是.format()的一些常见用法,它可以非常方便地对字符串进行格式化,使得输出更加可读和灵活。