A
A
AlmazKayum2020-07-29 16:07:28
Python
AlmazKayum, 2020-07-29 16:07:28

How do F strings in a variable work correctly?

Hello.
I have a line string1 = '{title} added. Which add more?'
It is stored in the database.
How can I make the string1 F variable a string so that the title variable will work?

I tried like this

string1 = '{title} added. Which add more?'
title = 'blabla'
print(f'{string1}')

But that doesn't work. title is displayed not as a variable, but as text.

It is necessary to alter a normal line in F a line in a variable.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
soremix, 2020-07-29
@AlmazKayum

string1.format(title=title)

Z
zx5zx6, 2020-07-29
@zx5zx6

string1 = f'{title} added. Which add more?'

T
Timur Pokrovsky, 2020-07-29
@Makaroshka007

https://pythonworld.ru/osnovy/formatirovanie-strok...

D
Dmitry, 2020-07-29
@LazyTalent

>>> def makef(nonf: str) -> str:
...     return eval(f'f"{nonf}"')
... 
>>> title = 'name'
>>> s = 'some {title}'
>>> print(makef(s))
some name

But you have to be very careful and validate everything that comes from the database

A
alekssamos, 2020-07-29
@alekssamos

>>> title = "asd"
>>> string1 = f'{title} added. Which add more?'
>>> print(string1)
asd added. Which add more?

And it works. It is possible without format.
Only if the user enters data in string1, there may be a problem, he can enter not intended, i.e. hidden variables like key, token, password, something like that. So be careful here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question