Home > Blockchain >  inserting a variable into an fstring using .replace()
inserting a variable into an fstring using .replace()

Time:01-27

I have a code something similar to bellow.

name = 'Dave'
message = f'<name> is a really great guy!'
message = message.replace('<name>', '{name}')
print(message)

the variables are a little more complicated than this, and a user (who may not be programming literate) will have entered into a variable via input(). I'm wanting to convert to {name} so fstring can handle the variable.

The expected output would be "Dave is a really great guy!". instead, its outputting "{name} is a really great guy!". Is there a way I can handle an issue like this?

CodePudding user response:

You seem to be confused about f-strings. An f-string interpolates variables right there in that literal. Consider f-strings as syntactic sugar over the operator:

message = f'{name} is a really great guy!'
message = name   ' is a really great guy!'

These two lines are equivalent for the purposes of this example. It takes the value of the name variable and bakes it into the string, then assigns the result to message. The result is a regular plain string. There's nothing "f-stringy" about message anymore, it's just the string 'Dave is a really great guy!'.

If you put some curly braces into the string afterwards, it will not be retroactively evaluated as an f-string replacement.

message = '<name> is a really great guy!'
message = message.replace('<name>', '{name}')

This is equivalent to what you're doing. Of course it will only replace "<name>" with "{name}". Literally like that.

Since you're doing replacement anyway, there's no point in using f-strings here. Just replace the placeholder <name> with the variable value:

message = '<name> is a really great guy!'
message = message.replace('<name>', name)
  • Related