0

I want to print the following using an f string literal. It will be running wihtin a function and apples will be one of the arguments. I want it to have the square brackets included.

"I like [apples] because they are green"

I have tried the following code:

"I like {} because they are green".format("apples")

The code above prints:

I like apples because they are green

How do I insert the square brackets [ ] or another special character such as < > into the f string literal?

Rick
  • 43,029
  • 15
  • 76
  • 119
machinelearner07
  • 113
  • 1
  • 1
  • 12
  • 4
    recognize that the "special character" is actually not special at all, it's just a string after all! If you need a string, it goes where all the other strings go. `"I like [{}] because they...` – Paritosh Singh Aug 05 '19 at 16:36
  • 1
    another way (kind of magical, but oh well) to do it is this: `"I like {} because they are green".format(["apples"])`. It adds the brackets because you passed a list instead of just the atomic string. – Rick Aug 05 '19 at 16:40
  • 1
    Building on the previous comment, the only characters that are actually "special" within a formatting string (besides escaped characters, like in any other string), are the placeholder characters `{` and `}`. If you want to use them literally you have to duplicate them, so for example to get `I like {apples}` you need to do `"I like {{{}}}".format("apples")` (three pairs of braces, two for the literal braces and one for the placeholder). – jdehesa Aug 05 '19 at 16:57

3 Answers3

2

There are a couple possible ways to do this:

"I like [{}] because they are green".format("apples") or "I like {} because they are green".format("[apples]").

If instead of brackets you wanted to use actual special characters, you would just have to escape in the appropriate place:

"I like {} because they are green".format("\"apples\"").

Additionally, if you wanted to use actual f-strings, you could do the same thing as above but with the format:

f"I like {'[apples]'} because they are green"

but make sure to switch from double quotes to single quotes inside the brackets to avoid causing troubles by ending your string early.

my name
  • 146
  • 4
0

Here are few suggestions on how to use special characters in f-string.

  1. If you want to print

Hello "world", how are you

var1 = "world"
print(f"Hello \"{var1}\", how are you") 
  1. To print:

Hello {world}, how are you

where world is a variable

var1 = world 
print(f"Hello {{var1}}, how are you")
  1. To print:

Hello {world}, how are you

where world is a constant

print(f"Hello ""{world""}, how are you")
D Dhaliwal
  • 552
  • 5
  • 23
Harita K
  • 1
  • 1
0

To print: Hello {world}, how are you

where world is a variable

var1 = world 
print(f"Hello {{var1}}, how are you")

is not correct. You have to add one extra bracket

var1 = world 
print(f"Hello {{{var1}}}, how are you")

since in f-string double brackets plots a single bracket