Reputation: 59
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"
Upvotes: 4
Views: 15625
Reputation: 799
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)
Upvotes: 7
Reputation: 1
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
Upvotes: 0
Reputation: 624
.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
Upvotes: 0
Reputation: 14927
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
Upvotes: 2
Reputation: 217
you can concat strings in python with +
data_file_format = sourcesystem + "_" + batchid + "_" + extractname + "_" + loadtype
this should give you "xyz_101_abc_Delta"
Upvotes: -1
Reputation: 8205
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)
Upvotes: 2