4

I have requirement where I am reading a string from json file and assign values to it to make it as a configurable file name.

String I am reading from json:

data_file_format =  "sourcesystem_batchid_extractname_loadtype"

I have variable which holds the values in my code like

sourcesystem ="xyz"
  batchid = "101"
  extractname = "abc"
  loadtype = "Delta"

so my data_file_format should yeild value like

data_file_format = "xyz_101_abc_Delta"
Sasidhar_gubbala
  • 59
  • 1
  • 1
  • 7
  • See this [post](https://stackoverflow.com/questions/2711579/how-can-strings-be-concatenated), particularly this [answer](https://stackoverflow.com/a/13881162/6942527). – busybear Dec 29 '18 at 07:11

6 Answers6

7

There are multiple methods to do that.:

fstring

data_file_format = f'{sourcesystem}_{batchid}_{extractname}_{loadtype}'

or using .format

data_file_format = '{}_{}_{}_{}'.format(sourcetype,batchid,extractname,loadtype)
ThunderMind
  • 789
  • 5
  • 14
2
sourcesystem ="xyz"
batchid = "101"
extractname = "abc"
loadtype = "Delta"
data_file_format="_".join([sourcesystem,batchid,extractname,loadtype])
#or
#data_file_format=sourcesystem+'_'+batchid +'_'+extractname+'_'+loadtype
print(data_file_format)
Bitto
  • 7,937
  • 1
  • 16
  • 38
2

So, you need to dynamically generate a file name based on an input data_file_format. Can you store your data in a dict instead of separate variables?

data_file_format =  "sourcesystem_batchid_extractname_loadtype"

data = {
  "sourcesystem": "xyz",
  "batchid": "101",
  "extractname": "abc",
  "loadtype": "Delta"
}

filename = '_'.join([data[key] for key in data_file_format.split('_')])

print(filename)

xyz_101_abc_Delta

ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
0

Or you can go basic and go ahead like,

data_file_format = datasourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype

The previous answer is not far off too. It just forgot the underscores

kiner_shah
  • 3,939
  • 7
  • 23
  • 37
0

.join would be the best answer in this scenario (the answer by bitto). But for the future some good methods are:

>>> a = 1
>>> b = 2
>>> c = "three"
>>> "%d and %d then %s" % (a, b, c)
1 and 2 then three
>>> "{} and {} then {}".format(a, b, c)
1 and 2 then three
>>> f"{a} and {b} then {c}"
1 and 2 then three
Joyal Mathew
  • 614
  • 7
  • 24
-1

you can concat strings in python with +

data_file_format =  sourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype

this should give you "xyz_101_abc_Delta"

Auxilus
  • 217
  • 2
  • 9