-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

6
  • 2
    That is not valid Python code, and it is unclear what you want. Commented Mar 8, 2017 at 1:24
  • The framing of the question isn't clear. Could you please tell us more about the difficulty you face? Commented Mar 8, 2017 at 1:24
  • Your code is not written in Python. Commented Mar 8, 2017 at 1: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. Commented Mar 8, 2017 at 1: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. Commented Mar 8, 2017 at 2:11

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.