0

I've seen this question but I think I have more nested quotes and it's doing my head in.

How would I convert the following line into an f-string?

file.write('python -c "{code}"'.format(code="open('test.txt', 'w');"))
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Mark Mayo
  • 12,230
  • 12
  • 54
  • 85
  • `s = "open('test.txt', 'w');"; f'python -c "{s}"'` -> `'python -c "open(\'test.txt\', \'w\');"'` – Ch3steR Nov 21 '22 at 01:02
  • `'python -c "{code}"'.format(code="open('test.txt', 'w');")` -> `'python -c "open(\'test.txt\', \'w\');"'` – Ch3steR Nov 21 '22 at 01:02

1 Answers1

1

There's barely anything to do here:

code="open('test.txt', 'w');"
file.write(f'python -c "{code}"')

You can of course also put the value of the variable in the f-string, but that would be silly:

file.write(f'python -c "{"open(\'test.txt\', \'w\');"}"')

Because replacing a string with a string is just, you know, inserting a string, no string formatting needed

file.write('python -c "open(\'test.txt\', \'w\');"')
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94
  • yeah, I guess I was going for option 2 but as you say, it's hardly doing anything useful. Thought originally f-strings didn't allow escape chars, but tis Monday and all bets are off mentally ;) – Mark Mayo Nov 21 '22 at 01:05
  • 1
    `f'python -c "{"open(\'test.txt\', \'w\');"}"'` is not valid this would throw `SyntaxError: f-string expression part cannot include a backslash` – Ch3steR Nov 21 '22 at 01:05
  • @Ch3steR is right, can't have escapes within an f-string :/ – Mark Mayo Nov 21 '22 at 01:11