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.
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"]}'
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.