如何正确使用Python .format()?

时间:2017-03-27 12:36:13

标签: python string python-3.x formatting

鉴于以下内容:

user_ = socket.gethostname()
runtime_ = time.ctime()
game_days = 'season open'
variable = 'speed'
start_time = datetime.time(15, 0)
weekdays = 'all days'
period = ['1/1/2013', '1/1/2020']

如何使用.format()查看this。为了得到这个输出

print(tag)

User-WS, Mon Mar 27 07:30:08 2017  US/Central - season open
Variable: speed At: 15:00. all days 1/1/2013:1/1/2020
--------------------------------------------------------

现在我正在做:

tag = user_ + ', ' + runtime_ + '  US/Central - ' + game_days + '\n' + 'Variable: '  + \ 
variable + ' At: ' + str(start_time)[:-3] + '. ' + weekdays + ' ' + period[0] + ':' + period[1] + '\n' + \
'--------------------------------------------------------'

1 个答案:

答案 0 :(得分:2)

s = '{}, {}, US/Central - {}\nVariable: {}, At: {}. {} {}:{}\n--------------------------------------------------------'

tag = s.format(user_, runtime_ game_days, variable, str(start_time)[:-3], weekdays, period[0],period[1])

这是一个非常全面的教程,你联系了,我不知道其中的一些。具体到底是什么让你苦苦挣扎?