Both ternaries ("if expressions") and comprehensions ("for expressions") are allowed inside f-strings. However, they must be part of expressions that evaluate to strings. For example, key: value is a dict pair, and f"{key}: {value}" is required to produce a string.
>>> dct = {'a': 1, 'b': 2}
>>> newline = "\n" # \escapes are not allowed inside f-strings
>>> print(f'{newline.join(f"{key}: {value}" for key, value in dct.items())}')
a: 1
b: 2
Note that if the entire f-string is a single format expression, it is simpler to just evaluate the expression directly.
>>> print("\n".join(f"{key}: {value}" for key, value in dct.items())))
a: 1
b: 2
Expressions inside format strings still follow their regular semantics. For example, a ternary may test whether an existing name is true. It will fail if the name is not defined.
>>> c, name = "Hello", ""
>>> f'{c} {name if name else "unknown"}'
'Hello unknown'
>>> del name
>>> f'{c} {name if name else "unknown"}'
NameError: name 'name' is not defined
Answer from MisterMiyagi on Stack Overflowusing f-string's with a list
Why do people use .format() method when f string literal exists?
f-string concatenating string variable outside for loop?
", you're replacing the value of route by a new string that starts with the current value of route. More on reddit.com
Purpose of the F-string
Videos
just thought id make a post incase anyone has an issue using f-string with a list. i moved on from using .format() to using f-string. i have found it pretty easy to get adjusted to but i was struggling with using specific values within a list, i treid a few methods like:
names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {0} {1} {2}'(*names)
print(text)
names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {*0} {*1} {*2}'(names)
print(text)
names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {[0]} {[1]} {[2]}'(names)
print(text)
all came back with errors and left me stuck on how to use f-string with a list until i watched Corey Schafers video, within the half an hour i was pretty much trying to brute force it, reaching the same error, i found out the correct way of interlopoing a list with a f-string is:
names = ['Adam', 'Bob', 'Cyril']
text = f'Winners are: {names[0]}, {names[1]}, {names[2]}'
print(text)
just thought id make the post incase anyone else is unsure on how.
Hello all,
I seem to encounter a lot of documentation and tutorials that use .format() method instead of f string literals.
Personally,
print("I can't seem to {} of a {} why someone {} {} {}".format('think', 'reason', 'would', 'prefer', 'this'))versus
easily = "easily"
sentence = "sentence"
this = "this"
print(f"A much more {easily} readable {sentence} such as {this}")F string literal is always much easier to decipher and thus avoid errors.
Perhaps there's some benefit of .format() that I'm unaware of. Googling hasn't brought up much on the debate.
Cheers!