iOSecure
iOSecure

Reputation: 232

Insert variable within a string in two locations

How would I get the year string in two locations in my filepath

year = str(date.today().year)
filename = r'output.csv\Year\{}.csv'.format(year)

It works with one bracket to change the {} to 2016.csv but

If I replace Year with a second {} to r'output.csv\{}\{}.csv'.format(year) it says IndexError: tuple index out of range

Upvotes: 2

Views: 51

Answers (1)

Lev Levitsky
Lev Levitsky

Reputation: 65791

Like this:

In [1]: 'output.csv/{0}/{0}.csv'.format(2016)
Out[1]: 'output.csv/2016/2016.csv'

With empty curly brackets, format just implies that each of the consecutive occurrences of {} corresponds to one of the positional arguments that you pass. If you want a different order, just specify an index explicitly.

String Formatting Docs

Also note that I am using slashes as separators, which is considered better practice with file paths, and that I used an int as year (so your conversion to str is unnecessary).

Upvotes: 4

Related Questions