user10543278
user10543278

Reputation:

Python - Format variable inside string

I have a problem. I want to assign a path to a variable, so I did this:

customers = ["john", "steve", "robbert", "benjamin"]
for customer in customers:
    dataset = "/var/www/test.nl/customer_data/" + str({customer}) + ".csv"

So I was hoping that the output of that variable would be:

/var/www/test.nl/customer_data/john.csv

But that's not the case, because the output I get is:

/var/www/test.nl/customer_data/set(['john']).csv

What am I doing wrong, and how can I fix this?

Upvotes: 1

Views: 87

Answers (2)

pdowling
pdowling

Reputation: 500

You have curly braces around the customer variable. Replace

dataset = "/var/www/test.nl/customer_data/" + str({customer}) + ".csv"

with

dataset = "/var/www/test.nl/customer_data/" + str(customer) + ".csv"

Better yet, if on python 3.6 or higher, use f strings:

dataset = f"/var/www/test.nl/customer_data/{customer}.csv"

That might be where you've seen curly braces used for string formatting. The way you're using them, you are defining a set object inline.

Upvotes: 2

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

Here you first make a singleton set that contains that string. As a result it is formatted the wrong way. With:

str({customer})

you thus first construct a set, for example:

>>> {"john"}
{'john'}
>>> type({"john"})
<class 'set'>

and if you then take the str(..) of that set, we get:

>>> str({"john"})
"{'john'}"

So then this is the value we will "fill in", whereas we only want the content of the string customer itself.

You can format these with:

customers = ["john", "steve", "robbert", "benjamin"]
for customer in customers:
    dataset = "/var/www/test.nl/customer_data/{}.csv".format(customer)

So here {} will be replaced with the string representation of customer, but since customer is already a string, it will thus simply fill in the string.

Upvotes: 2

Related Questions