1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.