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'

5
  • 1
    maybe print(eval(s)) Commented Sep 22, 2021 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 about them. Commented Sep 22, 2021 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
    Commented Sep 22, 2021 at 13:42
  • 2
    Looks like XY-problem... Where is the string s coming from?
    – bereal
    Commented Sep 22, 2021 at 13:45
  • it prints like that because you have that double quotes, just remove them and s will contain 1234 Commented Sep 22, 2021 at 13:45

7 Answers 7

1

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

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}"
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'.

1
0

You'd do this -

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

This can also work.

x = 3 
s = "12{}4"
print(s.format(x))
0

Just remove extra commas

s = f'12{x}4'
0
x = 3 
s = '12{}4'.format(x)

or

x = 3 
print('12%s4' %x)
1
  • This is not an answer to the question... Commented Sep 22, 2021 at 17:51

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.