Skip to main content
 首页 » 编程设计

python之管理 python 字符串中的关键字参数 : how to format only some arguments and keep the others unformatted

2025年05月04日35rubylouvre

我在理解字符串的 format() 方法的工作方式时遇到了一些麻烦。

假设我设置了一个带有关键字参数的字符串变量:

s = '{hello} {person_name}' 

我可以将此值分配给另一个变量或打印它。在后一种情况下,结果将是 {hello} {person_name}。

我还可以在打印 s 时使用 format() 方法并为关键字分配一些值:

print(s.format(hello='hello', person_name='Alice')) 

在这种情况下,结果是 hello Alice。当然,我也可以将它分配给一个新的变量。

当我只想对一个关键字使用格式时,我的问题就出现了:

print(s.format(hello='hello')) 

或

a = s.format(hello='hello') 

两者都抛出错误:

KeyError: 'person_name'


我希望能够运行类似的东西:

s = '{hello} {person_name}' 
a = s.format(hello='hello') 
if something: 
  b = a.format(person_name='Alice') 
else: 
  b = a.format(person_name='Bob') 
print(b) 

当我使用 format() 时,这样的事情是可能的还是我应该设置所有关键字?

请您参考如下方法:

在您的用例中,您可能会考虑转义字符串中的 {person}:

# double brace the person_name to escape it for the first format 
s = '{hello} {{person_name}}' 
a = s.format(hello='hello') 
 
# a = 'hello {person_name}' 
 
if something: 
  b = a.format(person_name='Alice') 
  # b = 'hello Alice' 
else: 
  b = a.format(person_name='Bob') 
  # b = 'hello Bob' 
 
print(b) 

然而,使用此方法时,您需要遵循转义变量的明确顺序。也就是说,您必须首先分配 hello 然后 person_name。如果您需要灵活处理事物的顺序,我建议使用 dict 在完全传递变量之前构造变量:

# dict approach 
s = '{hello} {person_name}' 
 
# determine the first variable 
d = {'hello':'hello'} 
... do something 
d.update({'person': 'Alice'}) 
 
# unpack the dictionary as kwargs into your format method 
b = s.format(**d) 
 
# b = 'hello Alice' 

这使您可以更灵活地处理事物的顺序。但是你必须只调用 .format() 一次 all 你的 dict 中提供了变量(至少它必须有一个默认值),否则它仍然会引发错误。

如果你想要更花哨,并希望能够在没有变量的情况下打印字段名称,你也可以制作自己的包装函数:

# wrapper approach 
# We'll make use of regex to keep things simple and versatile 
import re 
 
def my_format(message, **kwargs): 
 
    # build a regex pattern to catch words+digits within the braces {} 
    pat = re.compile('{[\w\d]+}') 
 
    # build a dictionary based on the identified variables within the message provided 
    msg_args = {v.strip('{}'): v for v in pat.findall(message)} 
 
    # update the dictionary with provided keyword args 
    msg_args.update(kwargs) 
 
    # ... and of course, print it 
    print(message.format(**msg_args)) 
 
s = 'Why {hello} there {person}' 
my_format(s, hello='hey') 
# Why hey there {person} 
 
my_format(s, person='Alice')  
# Why {hello} there Alice 

您可以通过修改字典理解中的 v 来确定您想要的默认显示(在没有变量的情况下)。