0
How to have { and ' into python f string
Hi I am using python f string as below: def testMethod(ch): return f'{ch}=' print(testMethod('B')) Above code helps me print B= as expected. What if I would need { and ' into this? Something like B='int' and {} is my expected output and hence I tried below: return f'{ch}='int' and {}' As Above was not working, I tried with backslash as below , but no success..! return f'{ch}=\'int\' and \{\}' Any solution of this?
6 Antworten
+ 5
You can double up the brace to have a single brace printed.
Backslash quotation mark \' prints a quotation mark. But also you can use the double-quotation mark as the string delimiter if you wish to include a single-quotation mark inside the string.
Working examples:
print(f' \'{{') # output: '{
print(f" '{{") # output: '{
And vice versa
print(f' "}}') # output: "}
+ 4
Here’s another one:
print(f"-> {chr(123) + 'hello' } '%' {chr(125)} <-\n\tworld!!!")
+ 3
Yet another, using the C-like metacharacter escape with octal values of the characters:
print(f'\042 \047 \173 \175')
# output
# " ' { }
This works inside ordinary strings too; not just f-strings.
+ 3
I didn't read your question carefully enough and though you want the method to print
{B}=
as the output.
I thought it was return f"\{{}\}=" at first but it failed.
With a little research, it uses double curly braces {{ and }} as escape character.
https://stackoverflow.com/questions/5466451/how-do-i-escape-curly-brace-characters-in-a-string-while-using-format-or
Thus, the method becomes:
def testMethod(ch):
return f"{{{ch}}}="
print(testMethod("B")) >>> {B}=
+ 3
To include curly braces `{}` and single quotes `'` inside an f-string in Python, you can escape them with double curly braces `{{}}` and double single quotes `''`. Here's how you can modify your code:
```python
def testMethod(ch):
return f"{ch}='int' and {{}}"
print(testMethod('B'))
```
This will print:
```
B='int' and {}
```
Using double curly braces `{{}}` escapes the curly braces and allows them to be included as literal characters in the string. Similarly, using double single quotes `''` escapes the single quotes and includes them as literal characters in the string.
+ 1
Thanks Brian . Exactly what I was looking for..
https://sololearn.com/compiler-playground/cN07aiL82rvp/?ref=app