【问题标题】:How to use Python .format() appropriately?如何正确使用 Python .format()?
【发布时间】:2017-08-20 04:12:39
【问题描述】:

鉴于以下情况:

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' + \
'--------------------------------------------------------'

【问题讨论】:

  • 你试过什么?通常,您只需将当前的' + name + ' 替换为占位符,就可以从连接转为格式化,这样您就有一个字符串,然后将所有名称传递给.format。这没有用吗?

标签: python string python-3.x formatting


【解决方案1】:
s = '{}, {}, US/Central - {}\nVariable: {}, At: {}. {} {}:{}\n--------------------------------------------------------'

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

您链接的教程非常详尽,我不知道其中一些。你具体遇到了什么困难?

【讨论】:

    猜你喜欢
    • 2014-12-31
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 2014-09-17
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多