首页 > 解决方案 > 如何将预定义的变量值传递到 Python 中预定义的硬编码字符串的一部分?

问题描述

我有下面的硬编码字符串,我从 MySql 中的配置表中读取。(并且我们的数据库中有许多硬编码 {},我不能去 mysql 识别所有变量并在脚本中手动处理它。)

    string_from_sql_table = '/distribution/{partner}/{process_date}/' 

我的 python 脚本中有以下预定义变量。

    from datetime import datetime
    string_from_sql_table = '/distribution/{partner}/{process_date}/' #to keep simple, didn't include code to read the string from mysql table. 
    partner = 'startupco'
    process_date = datetime.today().strftime('%Y%m%d_%H%M')

我打印时得到以下输出(string_from_sql_table):

    /distribution/{partner}/{process_date}/

如何在不更改输入 string_from_sql_table 或更改输入 string_from_sql_table 的情况下低于预期输出:

    /distribution/startupco/20191011_1317/

标签: python-3.6

解决方案


简单的

'/distribution/{partner}/{process_date}/'.format(
    partner = 'startupco', 
    process_date = datetime.today().strftime('%Y%m%d_%H%M')
)

在此处阅读有关该主题的更多信息https://docs.python.org/3/library/stdtypes.html#str.format


推荐阅读