【问题标题】:Python 3 Print VariablesPython 3 打印变量
【发布时间】:2013-07-23 22:13:51
【问题描述】:

有没有更好的方法在 python3 中打印变量集?

在 PHP 中,我经常这样做: echo "http://$username:$password@$server:$port"

但在 python 3 中,使用所有这些 + 输入看起来非常丑陋且更长

print('http://'+username+':'+password+'@'+server+':'+port)

在python中是否有类似“$”符号的东西?谢谢。

【问题讨论】:

    标签: python variables printing


    【解决方案1】:

    Python 不支持字符串插值,但您可以使用字符串格式化:

    'http://{}:{}@{}:{}'.format(username, password, server, port)
    

    或使用关键字参数(如果您已经在字典中有参数,则最好使用):

    'http://{username}:{password}@{server}:{port}'.format(
        username=username,
        password=password,
        server=server,
        port=port
    )
    

    你也可以稍微滥用locals(),但我不建议这样做:

    'http://{username}:{password}@{server}:{port}'.format(**locals())
    

    【讨论】:

    • 这对于某些代码来说要好得多 :-) 谢谢。但是为什么你不建议 locals() ?这似乎是最干净的方法^_^我很惊讶python没有为双引号中的简单变量提供更好的方法LOL
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2015-07-02
    • 2020-05-17
    • 2015-01-12
    相关资源
    最近更新 更多