1

How do I concatenate a variable and a string in Python?

cases = ['087360','095140']

for case in cases:
    case+'biofile' = pandas.read_csv(case+'/InputFiles/BioSave.csv')

I want this to store '087360biofile' and '095140biofile'.

DPdl
  • 723
  • 7
  • 23
  • 2
    You can't name variables like that. Use a dictionary instead. `my_dict = {case+'biofile': pandas.read_csv(case+'/InputFiles/BioSave.csv') for case in cases}`. Then access your elements like `my_dict['087360biofile']` – pault May 01 '18 at 15:07

2 Answers2

4

Is a dictionary good?

biofile = {}

for case in cases:
    biofile[case] =  pandas.read_csv(case+'/InputFiles/BioSave.csv')

Then you can access it as:

biofile['087360']
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25
4

You almost never want to do this, but if you really do - all variables in python are stored in dictionaries. You can directly access these dictionaries, for example the dictionary for local variables.

for case in cases:
    locals()[case+'biofile'] = pandas.read_csv(case+'/InputFiles/BioSave.csv')

But unfortunately this turns out to be useless! Not because of how we assigned it, but because the name starts with a number, which means we can't access it (except through the dictionary), because the python parser will try and split off the number as something separate. We could instead go with

for case in cases:
    locals()['biofile'+case] = pandas.read_csv(case+'/InputFiles/BioSave.csv')

Which would give you a valid python name (e.g biofile087360).

But it's much more natural (and probably what you want to do) to just put them in a dictionary

biofiles = {}
for case in cases:
    biofiles[case] = pandas.read_csv(case+'/InputFiles/BioSave.csv')
Probie
  • 1,371
  • 7
  • 15