2

Is there a better way to print set of variable in python3 ?

In PHP I useally did something like this: echo "http://$username:$password@$server:$port"

But in python 3 it looks very ugly and longer to type with all those +'s

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

Is there something like this in python like "$" symbol ? Thank you.

4

1 回答 1

4

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())
于 2013-07-23T22:17:17.923 回答