0

Suppose I have

x = 3 
s = "f'12{x}4'"

How to consider s as f-string to print 1234, like writing print(f'12{x}4') when I print s, it prints it as it as: f'12{x}4'

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • 1
    maybe `print(eval(s))` – Alexey S. Larionov Sep 22 '21 at 13:41
  • 2
    It is unclear what you are asking. An f string uses the format `s=f'12{3}4'`. It is not wrapped in quotation marks. Consider reading a [tutorial](https://realpython.com/python-f-strings/) about them. – blackbrandt Sep 22 '21 at 13:42
  • 3
    F-strings are a feature of the Python language. They work because interpreter (or compiler, or other runtime) understand the python source and know how to interpret that syntax. You can treat this string as python source code, and evaluate it with `eval(s)`, but doing so would be very suspicious. Why exactly would you want this? What are you trying to achieve? – Alexander Sep 22 '21 at 13:42
  • 2
    Looks like XY-problem... Where is the string `s` coming from? – bereal Sep 22 '21 at 13:45
  • it prints like that because you have that double quotes, just remove them and s will contain 1234 – Gerardo Zinno Sep 22 '21 at 13:45

7 Answers7

1

Remve the double quotations that should fix the issue because the f in a f string needs to be outside the actuall string

user15446500
  • 116
  • 5
1

You are missing two concepts.

  1. The first one, is how you tell python your string is an f-string. The way to do this, is by adding the character 'f' before the first quotation mark:
f"this will be a f-string"
  1. Whatever you have between {}, it will be a previously defined variable:
x = "something"
f"this will be {x}"
aleGpereira
  • 161
  • 1
  • 2
0

You'd do this -

x = 3
s = f'12{x}4'
alonkh2
  • 533
  • 2
  • 11
0

This can also work.

x = 3 
s = "12{}4"
print(s.format(x))
vnk
  • 1,060
  • 1
  • 6
  • 18
0

Just remove extra commas

s = f'12{x}4'
0

Assuming you ask this because you can not use actual f-strings, but also don't want to pass the parameters explicitly using format, maybe because you do not know which parameter are in the not-really-an-f-string, and also assuming you don't want to use eval, because, well, eval.

You could pass the variables in the locals or globals scope to format:

>>> x = 3
>>> s = '12{x}4'
>>> s.format(**globals())
'1234'
>>> s.format(**locals())
'1234'

Depending on where s is coming from (user input perhaps?) This might still be a bit risky, though, and it might be better to define a dict of "allowed" variables and use that in format. As with globals and locals, any unused variables do not matter.

>>> vars = {"x": x, "y": y, "z": z}
>>> s.format(**vars)

Note that this does not give you the full power of f-strings, though, which will also evaluate expressions. For instance, the above will not work for s = '12{x*x}4'.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0
x = 3 
s = '12{}4'.format(x)

or

x = 3 
print('12%s4' %x)