Include Variable In Text String In Python
I am trying to include the date in the name of a file. I'm using a variable called 'today'. When I'm using bash I can reference a variable in a long string of text like this: today
Solution 1:
You can add the strings together or use string formatting
output_file = '../../../output_files/aws_instance_list/aws-master-list-' + today + '.csv'
output_file = '../../../output_files/aws_instance_list/aws-master-list-{0}.csv'.format(today)
output_file = f'../../../output_files/aws_instance_list/aws-master-list-{today}.csv'
The last one will only work in Python >= 3.6
Solution 2:
In Python you use + to concat variables.
today = datetime.today()
today = today.strftime("%B %d %Y")
output_file = '../../../output_files/aws_instance_list/aws-master-list-' + today +'.csv'
Solution 3:
Give a look to: Python String Formatting Best Practices
Solution 4:
Not quite sure if thats what you mean, but in python you can either simply add the strings together
new_string=str1+ str2
or something like
new_string='some/location/path/etc/{}/etc//'.format(another_string)
Solution 5:
The closest Python equivalent to bash's
ofile="$output_dir"/aws-master-ebs-volumes-list-$today.csv
is
ofile=f'"{output_dir}"/aws-master-ebs-volumes-list-{today}.csv'
Only in Python 3.7 onwards.
Post a Comment for "Include Variable In Text String In Python"