Search code examples
pythonf-stringformat-string

Format of f string example


I have an example of f strings in textbook, it's a function whose purpose is to take a list and print the list out enumerated, I do not understand how the code is functioning but do know it works fine. I would like to understand a few things about this code:

import random
OPTIONS = ['rock', 'paper', 'scissors']

def print_options():
    print('\n'.join(f'({i}) {option.title()}' for i,option in enumerate(OPTIONS)))


print_options()

output:

(1) Rock
(2) Paper
(3) Scissors

the problem line is the body of the function. I would like to see how to modify the line but preserving the f-string method to leave out the enumeration, e.g.

desired output:

Rock
Paper
Scissors

All I can think of is:

def _print_choices():
    print('\n.join(f'({choice.title()}))' for choice in choices)

print_choices()

Which I can see from the amount of red in the editor is not even worth running.

Any ideas?


Solution

  • def print_options():
        print('\n'.join(option.title() for option in OPTIONS))
    
    # output: 
    # Rock 
    # Paper 
    # Scissors
    

    Since you don't want the index, the f-string and enumeration can be totally removed.