所以我遇到了一個問題,我試圖從 excel 電子表格中的單元格中清除一堆換行符。我的程式在遇到 \n 時識別它,但 .strip() 和 .replace('\n', '') 不起作用。我在這里缺少什么?
#!/usr/bin/env python3
""" Clean up undesired whitespace in some excel files """
from openpyxl import Workbook, load_workbook
Filename = input("Enter filename:\n")
wb = load_workbook(filename = Filename)
sheet = wb.active
max_row = sheet.max_row
max_column = sheet.max_column
for row in range(2, max_row 1):
for col in range(1, max_column 1):
print("In row: {} col: {}".format(row, col))
cell_obj = str(sheet.cell(row = row, column = col).value)
if cell_obj is not None:
if cell_obj[0] == ' ' or cell_obj[-1] == ' '
cell_obj.strip()
if '\n' in cell_obj:
cell_obj.replace('\n', '')
cell_obj.strip('\n')
if str('\n') in cell_obj:
cell_obj.replace(str('\n'), '')
if '\\n' in cell_obj:
cell_obj.strip('\\n')
sheet.cell(row=row, column=col).value = cell_obj
wb.save(filename=Filename)
uj5u.com熱心網友回復:
strip 和 replace 方法回傳轉換后的結果。它們不會作用于原始的不可變字串。你扔掉了結果。
>>> a = 'test\n'
>>> a.strip()
'test'
>>> a
'test\n'
>>> b = a.strip()
>>> b
'test'
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/328264.html
上一篇:Apache錯誤檔案自動重寫規則
