2

When I try to f'string dictionary, it says invalid syntax.

def up_low(s):
    d={"upper":0,"lower":0}
    for c in s:
        if c.isupper():
            d["upper"]+=1
            print (f"No. of Upper case characters: {d["upper"]}")
        elif c.islower():
            d["lower"]+=1
            print (f"No. of Lower case characters:{d["lower"]}")
        else:
            pass

it says invalid syntax for line 6 and line 9.

DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
Aaewatech
  • 17
  • 1
  • 1
    Use single quotes instead of double quotes for your key, like `d['upper']`. The string in which that appears is already in double quotes, so they are in conflict. You could also do the reverse, by single quoting the string instead, but I prefer the single quotes around the key. – Deepstop Sep 10 '19 at 18:07

3 Answers3

5

Don't use " in a string enclosed with ", either use ', or enclose the string in ':

f"No. of Upper case characters: {d['upper']}"

Or:

f'No. of Upper case characters: {d["upper"]}'
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

Change your double quotes to single quotes inside {d["upper"]}

Here is full working code:

def up_low(s):
    d={"upper":0,"lower":0}
    for c in s:
        if c.isupper():
            d["upper"]+=1
            print (f"No. of Upper case characters: {d['upper']}")
        elif c.islower():
            d["lower"]+=1
            print (f"No. of Lower case characters:{d['lower']}")
        else:
            pass

Matthew Gaiser
  • 4,558
  • 1
  • 18
  • 35
0

You can use any "other" string delimiter - even the triple ones:

d = {"k":"hello"}
print(f'''{d["k"]}''')
print(f"""{d["k"]}""")
print(f'{d["k"]}')
print(f"{d['k']}")

Output:

hello
hello
hello
hello

Using the same ones confuses python - it does not know where the f-string ends and your key-string starts if you use the same delimiters.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69