Python Forum

Full Version: Is it possible to have an apostrophe inside { } in an f-string?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
from random import choice as rc

string = f"never say you {rc(['can', 'can\'t'])} do something"

print(string)
Output:
File "C:/Users/Exsul/.PyCharmCE2019.2/config/scratches/scratch.py", line 3 string = f"never say you {rc(['can', 'can\'t'])}" ^ SyntaxError: f-string expression part cannot include a backslash Process finished with exit code 1
How can I put an apostrophe inside the curly brackets, since I can't escape an end quotation mark with \?
I got it to work by making the outer string a triple quoted string. But really, at this point I'd use a format call or another variable to hold the result of the random.choice call.
You can use chr() to convert the ASCII code 39 to an apostrophe:
string = f"never say you {rc(['can', 'can' + chr(39) + 't'])} do something"
Just a gentle nudging: it's not good practice to obscure code with cryptic abbreviations.

If code base grows and other people read the code they will need additional effort to mentally parse what the heck 'rc' does. There are conventions of using abbreviations ('import pandas as pd', 'import numpy as np') but I don't think that 'from random import choice as rc' is widespread convention.
and string is a module from Python Standard Library and should not be used as variable name
Error:
f-string expression part cannot include a backslash
Why not just read the error message properly and code accordingly?
And of course PEP8 and other coding standards are your friend.
from random import choice

can_or_cant = choice(['can', 'can\'t'])
sentence = f"never say you {can_or_cant} do something"
print(sentence)
Edit: OP question must be answered Yes, as this works without problems.
print(f"never say you can\'t do something")
(Sep-04-2019, 05:53 AM)perfringo Wrote: [ -> ]Just a gentle nudging: it's not good practice to obscure code with cryptic abbreviations.

If code base grows and other people read the code they will need additional effort to mentally parse what the heck 'rc' does. There are conventions of using abbreviations ('import pandas as pd', 'import numpy as np') but I don't think that 'from random import choice as rc' is widespread convention.

Oh, I would never do that on code I intended other people to see. This is a personal project.