Windy71
Windy71

Reputation: 909

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?

Upvotes: 1

Views: 327

Answers (2)

Eric Jin
Eric Jin

Reputation: 3934

OPTIONS = ('Rock', 'Paper', 'Scissors')
def _print_choices(OPTIONS, sep='\n'):
    print(sep.join([f'{choice.title()}' for choice in OPTIONS]))

Output:

>>> _print_choices(OPTIONS, '\n'):
Rock
Paper
Scissors

Upvotes: 1

Richard
Richard

Reputation: 225

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.

Upvotes: 2

Related Questions