Home > OS >  Why my List show a string separate the characters and showing it as list
Why my List show a string separate the characters and showing it as list

Time:06-15

My current csv file :

  'Date','Category','Ability' 
  '21,14,5','Sparrow','Air,land' 
  '4,5,6','Eagle','Air,Land'
  '21,14,5','Penguin','water,land'

my code:

Living_beings=[]
with open(users_read,'r') as f:
  reader=DictReader(f)
  for row in reader:
    if date.today().day in row['Date']:
         Living_beings =row['Category']
  print(Living_beings)

Output ; ['S','p','a','r','r','o','w','P','e','n','g','u','i','n']

Expected output: [Sparrow, penguin]

I am not sure why it was split up...Any ideas on this.

CodePudding user response:

The line Living_beings =row['Category'] treats the contents of row['Category'] as a list of characters (because it is a string), and extends the Living_beings list with the row['Category'] list of characters.

Instead, you should use:

Living_beings.append(row['Category'])

CodePudding user response:

Try Living_beings.append(row['Category']) instead.

My suspicion is the original code is treating row['Category'] as a list of individual characters so it can combine the lists.

  • Related