I would like to replace it to eliminate half-width and full-width hyphens from strings such as "a-i-u" in xlsx.
I get an error when I put in multiple conditions as shown below, but is there a way to replace them all together under multiple conditions?
wb=openpyxl.load_workbook('book.xlsx')
ws = wb.worksheets [0]
ifos.listdir('Folder with Files'):
for i in range (ws.max_row):
for row in ws.iter_rows():
for cell in row:
#6 is the column where the string you want to replace exists.
ifcell.col_idx==6:
# substituted portion
text=cell.value.replace(["-", "-", "")
cell.value=text
·Error code
text=cell.value.replace(["-", "-"], "")
TypeError: replace() argument 1 must be str, not list
If the replacement part can be divided into multiple parts such as text2, then there is no problem with that method.
python python3 openpyxl
Wouldn't it be better to replace (delete) the re
module?
I want to delete multiple strings in Python -
import re
and you will be able to do this
text=re.sub(r"[--]", ", cell.value)
cell.value=text
Alternatively, translate provides a batch replacement method.
Note: Replace, translate, re.sub, re.subn
import openpyxl
wb=openpyxl.load_workbook('Book1.xlsx')
ws = wb.worksheets [0]
hyphens=["-", "-" ]
trans=str.maketrans({"-":", "-":"})
For in range (ws.max_row):
#6 is the column where the string you want to replace exists.
cell=ws.cell (row=r+1, column=6)
ifcell.value!=None:
# substituted portion
cell.value=cell.value.translate(trans)
# Save Overwrite
wb.save ('Book 1.xlsx')
© 2024 OneMinuteCode. All rights reserved.