|
发表于 2024-9-8 12:56:13
|
显示全部楼层
本楼为最佳答案
 球最佳
- 当然,这里我将分别给出一个使用format方法和f-string(格式化字符串字面量)的例子来展示如何在Python中进行字符串格式化。
- 使用format方法
- format方法允许你通过指定占位符(如{})并在format方法中提供对应的值来格式化字符串。你可以通过位置参数、关键字参数或者同时使用它们来指定值。
- 例子:
- python
- name = "Alice"
- age = 30
-
- # 使用位置参数
- greeting = "Hello, {}! You are {} years old.".format(name, age)
- print(greeting) # 输出: Hello, Alice! You are 30 years old.
-
- # 使用关键字参数
- greeting_kw = "Hello, {name}! You are {age} years old.".format(name=name, age=age)
- print(greeting_kw) # 输出: Hello, Alice! You are 30 years old.
-
- # 也可以混合使用
- greeting_mixed = "Hello, {0}! You are {age} years old and live in {1}.".format(name, "Wonderland", age=age)
- print(greeting_mixed) # 输出: Hello, Alice! You are 30 years old and live in Wonderland.
- 使用f-string
- 从Python 3.6开始,f-string提供了一种非常简洁和易读的方式来嵌入表达式到字符串常量中。f-string以f或F为前缀,并在字符串内使用大括号{}来包含表达式。
- 例子:
- python
- name = "Bob"
- age = 25
-
- # 使用f-string
- greeting_f = f"Hello, {name}! You are {age} years old."
- print(greeting_f) # 输出: Hello, Bob! You are 25 years old.
-
- # f-string中也可以包含表达式
- square = 5
- greeting_f_expr = f"The square of {square} is {square**2}."
- print(greeting_f_expr) # 输出: The square of 5 is 25.
-
- # 调用函数
- def get_greeting(name):
- return f"Hi, {name}!"
-
- print(get_greeting("Charlie")) # 输出: Hi, Charlie!
- f-string因其简洁性和性能优势(相对于其他字符串格式化方法),在Python 3.6及以上版本中非常受欢迎。
复制代码 |
|