Search code examples
pythonexcelpywin32

Replcae string using table in pywin32 of Python like =IFS(A1='CA','California',A1='AL', 'Alabama',A1='NY', 'New York')


Newbie here

I assume this is a case like when you want to use translate(string.maketrans) but you want to replace some words with more than a character.

I'm trying to automate simple excel task, where is required to translate/replace certain words.

I know there are many ways to do this such as with for loop or excel formula itself when I'm using win32 but I tried below thinking it's more simple and just don't logically understand why it cannot work.

trans={'CA':'California','TX':'Texas','NY':'New York'}  
wb2.Range('F10').value=str(wb1.Range('F2')).translate(trans)

Returns no errors but happens nothing in wb2.Range('F10') →actually value of F2(in sheet1) will be just copied to F10(in sheet2) without replacement.

Can anyone help me out?

Thank you.


Solution

  • Since you have the data in dictionary you can directly call it as dict[element].

    >>> trans['CA']
    >>> 'California'
    

    Code:

    trans={'CA':'California','TX':'Texas','NY':'New York'}  
    wb2.Range('F10').value= trans[str(wb1.Range('F2'))]