alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[923] f-strings in Python

ref: f-strings in Python

ref: Python's F-String for String Interpolation and Formatting


F-strings, also known as formatted string literals, are a feature introduced in Python 3.6 that provide a concise and convenient way to embed expressions inside string literals. F-strings are often used for string interpolation, making it easy to insert variables and expressions into strings. They are created by prefixing a string with the letter 'f' or 'F' and enclosing expressions in curly braces {}.

Here's a basic example of how to use f-strings in Python:

name = "Alice"
age = 30
# Create an f-string
greeting = f"Hello, my name is {name} and I am {age} years old."
print(greeting)

In this example, the f-string greeting contains placeholders {name} and {age}. When the f-string is evaluated and printed, these placeholders are replaced with the values of the corresponding variables, resulting in the final string "Hello, my name is Alice and I am 30 years old."

F-strings offer several advantages:

  1. Readability: F-strings make the code more readable and concise, as you can embed variables directly within the string, making it clear what's being inserted.

  2. Expressions: You can include expressions, not just variables, within the curly braces. This allows you to perform calculations or format values directly within the string.

    num1 = 10
    num2 = 20
    result = f"The sum of {num1} and {num2} is {num1 + num2}."
  3. Formatting: F-strings support various formatting options for numbers, dates, and other data types. For example, you can format floating-point numbers to a specific decimal place or dates in a particular format.

    price = 49.99
    formatted_price = f"The price is ${price:.2f}"
  4. Multiline Strings: F-strings can also be used for multiline strings, making it easy to create formatted text with line breaks and indentation.

    message = f"""Dear {name},
    Thank you for your order.
    Sincerely,
    Your Company"""

Keep in mind that f-strings are available in Python 3.6 and later versions. They are a powerful tool for string formatting and are widely used in modern Python code for their readability and flexibility.

posted on   McDelfino  阅读(12)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-10-23 【760】Transformer,seq2seq,Attention,Encoder-Decoder连接
2022-10-23 【759】seq2seq(编码器和解码器)和注意力机制
2022-10-23 【758】Transformer结构图
2019-10-23 【444】Data Analysis (shp, arcpy)
点击右上角即可分享
微信分享提示