4

Is there a way to avoid having to escape literal curly brackets characters in a python3 f-string?

For example if you want to output a json string or a chunk of CSS rules it's really inconvenient to have to convert all the { and } characters to {{ and }} in case you want to use the f-string syntax.

I am aware that one can use the older syntax of e.g. div {color: %s} % color, 'text {}'.format(abc) or string templates but I wonder if there is a way to use the f-strings on raw text, preferably by having a way to mark the beginning and end of the 'raw' blocks with some kind of delimiter, for example similar to how you can use \Q and \E in a java regex in order to include unescaped raw characters in the regex.

As an alternative, is there something in the standard library that allows taking a chunk of raw text and converting it to an f-string-safe format? (again, similar to how you can use Pattern.quote for java regexes)

ccpizza
  • 28,968
  • 18
  • 162
  • 169

2 Answers2

5

One can use implicit string concatenation to apply f-string formatting to only parts of a string.

[...] Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings), and formatted string literals may be concatenated with plain string literals.

>>> hello = "world"
>>> "{hello}" f"{hello}" "!"
'{hello}world!'

This uses the exact same bytecode as the respective f-string with escapes. Note that the whitespace is optional, but helpful for readability.

MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
0

There are three ways in python in which you can manupulate a string.

  1. using f string
  2. using str.format expressions
  3. %-formatting expression

please refer to this link

Incase if you want, you can make your own custom function and call it.

def format_string(data,template):
    for key, value in data.items():
    return template.replace("#%s#" % key, str(value))
    
    
template ="<html><body>name is :#name# , profession is :#profession#<body></html>"
data ={"name":"Jack","profession":"student"}    
format_string(data,template)
subhanshu kumar
  • 372
  • 3
  • 10
  • 2
    I'm familiar with the existing formatting approaches. The question is specifically about ways to enable/disable f-string magic for specific blocks _or_ ootb ways to make any text 'f-string'-safe. – ccpizza Aug 08 '20 at 14:48