-4

referring to the code below, How do I replace the variable in [] to numerical values using python?

var LVdemact=[ Home1,  Home2,  Home3,  Home4,  Home5] 

The values that should replace the number of 'Home' is from an Excel file.

Sorry I have not much experience programming in python

  • 2
    That is not valid Python code, and it is unclear what you want. – juanpa.arrivillaga Mar 08 '17 at 01:24
  • The framing of the question isn't clear. Could you please tell us more about the difficulty you face? – Suraj Mar 08 '17 at 01:24
  • Your code is not written in Python. – DYZ Mar 08 '17 at 01:24
  • Are you asking how to change each item in a list to another type? If so, you can just do [int(x) for x in LVdemact] to change them to ints (change int to float to do float instead). But as others have mentioned, your code isn't python, so I don't know if that's what you're asking. – Kewl Mar 08 '17 at 01:35
  • My apology for not stating it clearer. The code above is inside a text file which I would like to replace the strings with some values. For example, I would like Python to read the text file and then change the Home1 to 1234, Home2 to 435, etc etc. – Shakree Elmi Mar 08 '17 at 02:11
  • Maybe helpful: [Modify an existing Excel file using Openpyxl in Python](http://stackoverflow.com/questions/13381384/modify-an-existing-excel-file-using-openpyxl-in-python), [Edit existing excel workbooks and sheets with xlrd and xlwt](http://stackoverflow.com/questions/26957831/edit-existing-excel-workbooks-and-sheets-with-xlrd-and-xlwt) – chickity china chinese chicken Mar 08 '17 at 02:20

1 Answers1

2

It sounds best suited to use a dictionary to map the values from: to. This seems to be what you've described:

from xlrd import open_workbook
from xlutils.copy import copy
import xlsxwriter

rb = open_workbook("Workbook1.xlsx")

# Create an new Excel file and add a worksheet.
wb = xlsxwriter.Workbook('Updated_Workbook1.xlsx')
ws = wb.add_worksheet()

s_orig = rb.sheet_by_index(0)

LVdemact = {'Home1': 1234, 'Home2': 435, 'Home3': 346, 'Home4': 768, 'Home5': 876}

for row in range(s_orig.nrows):
    for col in range(s_orig.ncols):
        if s_orig.cell(row,col).value in LVdemact:
            # s.write(row, col, LVdemact[item])
            ws.write(row, col, LVdemact[s_orig.cell(row,col).value])
        else:
            ws.write(row, col, s_orig.cell(row,col).value)
wb.close()

Original: Original Excel Document Modified: Modified Excel Document