You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何实现带灵活{}调整的格式化字符串?

Flexible Formatting for Strings in Python

Absolutely! Python has several great ways to build flexible formatted strings—perfect for cases like your "A与B之间的距离" example where you want more control than basic placeholder setup. Let’s walk through the most practical approaches:

1. Keyword Placeholders (Simplest & Most Readable)

Both f-strings (Python 3.6+) and str.format() support keyword arguments, which let you reuse values and tweak the string structure easily. For your distance example:

# Using f-strings (cleanest for most cases)
obj_a = "北京"
obj_b = "上海"
distance = 1318
distance_str = f"{obj_a}与{obj_b}之间的距离是{distance}米"
print(distance_str)  # 输出: 北京与上海之间的距离是1318米

# Using str.format() (great for reusing templates)
template = "{x}与{y}之间的距离是{d}米"
result = template.format(x="广州", y="深圳", d=147)
print(result)  # 输出: 广州与深圳之间的距离是147米

Want to make the relationship phrase dynamic too? Just add another placeholder:

relation = "和"
metric = "高度差"
result = f"{obj_a}{relation}{obj_b}的{metric}是50厘米"
print(result)  # 输出: 北京和上海的高度差是50厘米

2. Custom Logic with Formatters

If you need to adjust output based on conditions (like switching units for large distances), create a custom formatter class or use format_map():

class SmartDistance:
    def __init__(self, obj1, obj2, distance):
        self.obj1 = obj1
        self.obj2 = obj2
        self.distance = distance
    
    def __getitem__(self, key):
        if key == "display":
            if self.distance < 1000:
                return f"{self.distance}米"
            else:
                return f"{self.distance/1000:.1f}千米"
        return getattr(self, key)

formatter = SmartDistance("西安", "乌鲁木齐", 2560)
result = "{obj1}到{obj2}的距离是{display}".format_map(formatter)
print(result)  # 输出: 西安到乌鲁木齐的距离是2.6千米

3. Jinja2 Templates (For Complex Scenarios)

For multi-line text, conditional sections, or loops, the Jinja2 template engine is a powerful tool. It’s not just for web dev—works great for any advanced string formatting:

First install it: pip install jinja2

Then use it like this:

from jinja2 import Template

template = Template("""
{% if distance < 1000 %}
{{ obj1 }}与{{ obj2 }}之间的距离是{{ distance }}米
{% else %}
{{ obj1 }}到{{ obj2 }}的距离约为{{ (distance/1000)|round(1) }}千米
{% endif %}
""")

short_dist = template.render(obj1="成都", obj2="重庆", distance=266)
print(short_dist.strip())  # 输出: 成都与重庆之间的距离是266米

4. String.Template (Safe for User-Provided Templates)

If you’re working with templates from untrusted sources (like user input), string.Template avoids the security risks of format strings:

from string import Template

template = Template("$obj1与$obj2之间的距离是$distance米")
result = template.substitute(obj1="杭州", obj2="南京", distance=279)
print(result)  # 输出: 杭州与南京之间的距离是279米

Quick Recommendation

  • Everyday use: Stick with f-strings—they’re concise and readable.
  • Reusable templates: Use str.format() with keyword args.
  • Conditional/logic-based formatting: Go with custom formatters or Jinja2.
  • User-provided templates: Use string.Template for safety.

All these methods let you build strings that adapt to your exact needs, way beyond basic placeholder replacement.

内容的提问来源于stack exchange,提问作者NewNewton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:50:20