f字符串例子的格式
Format of f string example
我在教科书中有一个 f 字符串的例子,它是一个函数,其目的是获取一个列表并打印出枚举的列表,我不明白代码是如何工作的,但知道它工作正常。我想了解有关这段代码的一些事情:
import random
OPTIONS = ['rock', 'paper', 'scissors']
def print_options():
print('\n'.join(f'({i}) {option.title()}' for i,option in enumerate(OPTIONS)))
print_options()
输出:
(1) Rock
(2) Paper
(3) Scissors
问题行是函数体。我想看看如何修改该行但保留 f-string 方法以省略枚举,例如
期望的输出:
Rock
Paper
Scissors
我能想到的是:
def _print_choices():
print('\n.join(f'({choice.title()}))' for choice in choices)
print_choices()
从编辑器中的红色数量来看,我什至不值运行。
有什么想法吗?
def print_options():
print('\n'.join(option.title() for option in OPTIONS))
# output:
# Rock
# Paper
# Scissors
因为不需要索引,f-string 和枚举可以完全去掉。
OPTIONS = ('Rock', 'Paper', 'Scissors')
def _print_choices(OPTIONS, sep='\n'):
print(sep.join([f'{choice.title()}' for choice in OPTIONS]))
输出:
>>> _print_choices(OPTIONS, '\n'):
Rock
Paper
Scissors
我在教科书中有一个 f 字符串的例子,它是一个函数,其目的是获取一个列表并打印出枚举的列表,我不明白代码是如何工作的,但知道它工作正常。我想了解有关这段代码的一些事情:
import random
OPTIONS = ['rock', 'paper', 'scissors']
def print_options():
print('\n'.join(f'({i}) {option.title()}' for i,option in enumerate(OPTIONS)))
print_options()
输出:
(1) Rock
(2) Paper
(3) Scissors
问题行是函数体。我想看看如何修改该行但保留 f-string 方法以省略枚举,例如
期望的输出:
Rock
Paper
Scissors
我能想到的是:
def _print_choices():
print('\n.join(f'({choice.title()}))' for choice in choices)
print_choices()
从编辑器中的红色数量来看,我什至不值运行。
有什么想法吗?
def print_options():
print('\n'.join(option.title() for option in OPTIONS))
# output:
# Rock
# Paper
# Scissors
因为不需要索引,f-string 和枚举可以完全去掉。
OPTIONS = ('Rock', 'Paper', 'Scissors')
def _print_choices(OPTIONS, sep='\n'):
print(sep.join([f'{choice.title()}' for choice in OPTIONS]))
输出:
>>> _print_choices(OPTIONS, '\n'):
Rock
Paper
Scissors