Home > database >  Python fancy strings
Python fancy strings

Time:07-25

How can I use Python's fancy strings in this case?

Example:

I have a list of f-string in a consts.py file:

commands = [f"{prefix}...", f"{prefix}...", ...]

main.py:

import consts
consts.commands[0] = ...

Can I somehow set "prefix" in commands from main, or do I need to define "prefix" first in consts and access it from main using consts.prefix = ...

CodePudding user response:

In an f-string, the fields are evaluated immediately:

> x = 3
> f'x = {x}'
'x = 3'

If you want to defer the evaluation, use an ordinary str literal, and use the format method later.

> s = 'x = {x}'
> s
'x = {x}'
> s.format(x=3)
'x = 3'
  • Related