Tux
Tux

Reputation: 247

Python 3 Print Variables

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.

Upvotes: 2

Views: 2718

Answers (1)

Blender
Blender

Reputation: 298046

Python doesn't support string interpolation, but you can do it with string formatting:

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

Or with keyword arguments (best used if you already have the arguments in a dictionary):

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

You could also abuse locals() a little, but I wouldn't suggest doing it this way:

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

Upvotes: 4

Related Questions