Home > Mobile >  Adding position of an item on a list to a list in Python
Adding position of an item on a list to a list in Python

Time:05-05

I would like to add a number at the end of a item in the list i'm creating like so:

import datetime as dt

current_date = dt.date.today()
string_date = current_date.strftime(('%B%d%Y'))

listSONO = []
NumberOfLoops = 2
BaseSONO = "AutoSO_"   string_date

for x in range(NumberOfLoops):
    listSONO.append(BaseSONO)

print(listSONO)

i would like it to look like [AutoSO_currentdate_01, AutoSO_currentdate_02, AutoSO_currentdate_03....] And so on created for the number of loops mentioned above. id be grateful for all help

CodePudding user response:

You could use a Formatted String Literal (f-string):

import datetime as dt

current_date = dt.date.today()
string_date = current_date.strftime('%B%d%Y')

listSONO = []
NumberOfLoops = 2
BaseSONO = "AutoSO_"   string_date

for x in range(1, NumberOfLoops   1):
    listSONO.append(f'{BaseSONO}_{x:0>2}')

print(listSONO)

Furthermore, you could also use a list comprehension which may be more pythonic:

import datetime as dt

current_date = dt.date.today()
string_date = current_date.strftime('%B%d%Y')
num_loops = 2
list_sono = [f'AutoSO_{string_date}_{x:0>2}' for x in range(1, num_loops   1)]
print(list_sono)

Output for both versions:

['AutoSO_May042022_01', 'AutoSO_May042022_02']
  • Related