'How to make string format exception in py

OK, 1st of all see my code

msg = '{username} joined {servername} {extra}'

value = {'username': '@Random', 'servername': 'AnyName'}
msg = msg.format(**value)
print(msg)

This code throwing this error

msg = msg.format(**value)
KeyError: 'extra'

My code work perfectly fine if I don't put {extra} in msg but it necessary to add sometime like that and it should not change. I know I can do this by adding {{extra}} but it should not be.

Please anyone help me!



Solution 1:[1]

Think you are looking for something like this:

msg = '{username} joined {servername} {{extra}}'

value = {'username': '@Random', 'servername': 'AnyName','{extra}': 'X'}
text = msg.format(**value)
print(text)

print(text.format(extra="Anything")) # if you want to print anything for extra
  • Output:
@Random joined AnyName {extra}
@Random joined AnyName Anything

Solution 2:[2]

It's not possible but you can use this version:

msg = '{username} joined {servername} {extra}'

value = {'username': '@Random', 'servername': 'AnyName'}
msg = msg.format(**{**{'extra': ''}, **value})
print(msg)

# Output
@Random joined AnyName 

Since Python 3.9, you can merge dict

msg = '{username} joined {servername} {extra}'

value = {'username': '@Random', 'servername': 'AnyName'}
msg = msg.format(**{'extra': ''} | value)
print(msg)

# Output
@Random joined AnyName 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tasrif
Solution 2 Corralien