简体   繁体   English

如何从Excel的单元格中删除某些字符

[英]How to remove certain characters from cell on Excel

I am new to python and I am trying to run a program that runs down a list of values on Excel, and removes the "^" character from every index. 我是python的新手,正在尝试运行一个程序,该程序在Excel上的值列表中运行,并从每个索引中删除“ ^”字符。 For example, if i have a column that has the following values (MS144573^, MS655072^, MS655282^, MS655177^, MS655073^) I would like each value to be replaced to (MS144573, MS655072, MS655282, MS655177, MS655073). 例如,如果我有一个具有以下值的列(MS144573 ^,MS655072 ^,MS655282 ^,MS655177 ^,MS655073 ^),我希望将每个值替换为(MS144573,MS655072,MS655282,MS655177,MS655073)。

I am using the Openpyxl module. 我正在使用Openpyxl模块。

I cannot identify whether cells in Excel are strings, are characters. 我无法确定Excel中的单元格是字符串还是字符。 Any ideas? 有任何想法吗?

i have tried the following code: 我尝试了以下代码:

import openpyxl
from openpyxl import workbook
path = "C:/Users/x/Desktop/x/x.xlsx"
wb = openpyxl.load_workbook(path)
sheet_read = wb.get_sheet_by_name("report")
sheet_write = wb.active


for i in range(1, 10):
 x = sheet_write.cell(row = i, column = 1).value
 y = len(x)
 if x[y] == '^':
    x = x[:y-1]

But i get this error: 但是我得到这个错误:

^ y = len(x) TypeError: object of type 'NoneType' has no len()` ^ y = len(x)TypeError:类型为“ NoneType”的对象没有len()`

You should use the re module. 您应该使用re模块。

import re

value = re.sub('^', '', input)   # where input is the values that you want substituted

This would replace all instances of ^ with nothing, effectively removing it, and storing it in value. 这将完全替换^所有实例,将其有效删除,并将其存储在值中。 If you have more than one to do you can iterate through the list and simply append them to a new list of cleaned values. 如果您要执行的操作不只一个,则可以遍历列表并将其附加到新的已清除值列表中。

EDIT: If you need more info on how to do this leave a comment and ill update the code to reflect your question. 编辑:如果您需要有关如何执行此操作的更多信息,请留下评论,并不良更新代码以反映您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM