Ibaboiii
Ibaboiii

Reputation: 89

Remove/Delete blank items in a list and print these values with a pattern in an excel file

basically I have these (sample) list of 'strings' NOT 'integers' of data:

[0]  
[1]  
[2]  
[3]  
[4]  
[5]  
[6]  47
[7]  49
[8]  51
[9]  53
[10]  55
[11]  57
[12]  59
[13]  61
[14]  63
[15]  65

In this case I cannot modify the data and just remove the white/blank space seen from index 0-5. I've researched quite a bit and I know that strings are immutable and I can't come up with a solution sadly. I will be transferring these output to an Excel file also. These white/blank space affects me transferring these to the excel file since it recognizes the white space as string which populates the first 6 cells with blank values.

Sample result from Excel file

Also I have difficulties in creating a pattern to populate these data in these format:

Supposed to be pattern of data in Excel

I'm using openpyxl and I've achieved populating them by column using a loop:

File_path = 'somepath'
Excel_file = openpyxl.load_workbook(File_path)
Sheet = excel_file.get_sheet_by_name('Sheet1')

col = 1
for data in Sample_list:
   Sheet.cell(row = 1, column = col).value = data
   col+=1

   if col == 16:
      Excel_file.save(File_path)
      break

Thank you in advance

Upvotes: 0

Views: 107

Answers (1)

entropy
entropy

Reputation: 850

Inside your loop, you can use isspace to check if the element is only spaces(or even tabs and newlines) before updating it in the excel:

# This will fill rows 1 and 3 but you can change that as per your use case
count = 0
for data in Sample_list:
    if not data or data.isspace():
        continue
    Sheet.cell(row = 1 if count % 2 == 0 else 3, column = col).value = data
    col+=count % 2 # Column only increments when count is odd
    count+=1

OR you can remove all the space strings from the list beforehand:

Sample_list = [elem for elem in Sample_list if not elem.isspace()]

Upvotes: 1

Related Questions