-1

I need print(f"" + xx) to output text aaa but it outputs {x} how could i make this work?

I have tried with printf and .format but couln't make any of those to work

x = "aa"
xx = "text {x}"
x = "aaa"
print(f"" + xx)
Alex W
  • 37,233
  • 13
  • 109
  • 109
TheGamerX
  • 23
  • 5
  • 2
    I can't tell what you're trying to accomplish with that code. – dfundako Sep 10 '19 at 18:29
  • The `xx` needs to be inside a `f" ... "` block otherwise it won't be interpolated – Alex W Sep 10 '19 at 18:33
  • Possible duplicate of [How do I convert a string into an f-string](https://stackoverflow.com/questions/47339121/how-do-i-convert-a-string-into-an-f-string) – Havenard Sep 10 '19 at 18:36
  • 1
    what is your python version ? It won't work if it is lesser 3.6. Since formatted string literals were added in python 3.6. https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals – rprakash Sep 10 '19 at 18:38

2 Answers2

1

You need to put the variable you are trying to print within f"{}":

x = "aa"
xx = "{x}"
x = "aaa"
print(f"{x}")

Otherwise, xx is literally "{x}" and is not expanded.

Anoop R Desai
  • 712
  • 5
  • 18
0

I think you want to use str.format, not an f-string.

xx = "text {x}"
x = "aaa"
print(xx.format(x=x))  # -> text aaa

Or without passing x explicitly:

print(xx.format(**locals()))  # -> text aaa
wjandrea
  • 28,235
  • 9
  • 60
  • 81