Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

inserting a variable into an fstring using .replace()

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading