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?

15th Mar 2024, 7:04 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 ответов
+ 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: "}
15th Mar 2024, 7:24 AM
Brian
Brian - avatar
+ 4
Here’s another one: print(f"-> {chr(123) + 'hello' } '%' {chr(125)} <-\n\tworld!!!")
15th Mar 2024, 11:43 AM
Per Bratthammar
Per Bratthammar - avatar
+ 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.
15th Mar 2024, 3:37 PM
Brian
Brian - avatar
+ 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}=
16th Mar 2024, 8:49 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 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.
16th Mar 2024, 11:54 AM
Rohit Krishna
Rohit Krishna - avatar
+ 1
15th Mar 2024, 7:40 AM
Ketan Lalcheta
Ketan Lalcheta - avatar