【问题标题】:TypeError: descriptor 'replace' requires a 'str' object but received a 'NoneType 'TypeError:描述符“replace”需要一个“str”对象但收到一个“NoneType”
【发布时间】:2018-09-23 11:12:51
【问题描述】:

我正在尝试使用 python 从远程 oracle 数据库直接查询的元组列表中的值 '\x1c' 替换为空格 (" ")。我收到此错误:

TypeError: descriptor 'replace' requires a 'str' object but received a 'NoneType '

下面是我正在使用的代码,错误来自的最后一行代码:

connection = cx_Oracle.connect("WELCOME", "welcome", "(ABC)")
cursor = connection.cursor()
querystring = "select CUST_OR_CARD_ID,MESG from tbaadm.rtt where 
SYSTEM_DATE_TIME >= '01/JAN/18' and dcc_id='SPR'"
cursor.execute(querystring)
col=cursor.fetchall()

col = [tuple(map(lambda i: str.replace(i, "\x1c"," "), tup)) for tup in col]

【问题讨论】:

  • 出于好奇,元组元素的实际数据类型是什么?替换 '\x1c' 的意图听起来像是可能需要解码的字节对象。
  • 我很好奇,我的解决方案如何运作?另外如果需要DataFrame 最好不要使用pd.read_sql

标签: python oracle pandas numpy


【解决方案1】:

我认为元组中有Nones,所以需要过滤掉它

col = [tuple([str.replace(i, "\x1c"," ") for i in tup if pd.notnull(i)]) for tup in col]

或仅replaceNones 值:

col=[tuple([str.replace(i, "\x1c"," ") if pd.notnull(i) else i for i in tup ]) for tup in col]

编辑:感谢@Paul Cornelius 的建议使用string.replace

col = [tuple([i.replace("\x1c"," ") for i in tup if pd.notnull(i)]) for tup in col]

col = [tuple([i.replace("\x1c"," ") if pd.notnull(i) else i for i in tup ]) for tup in col]

【讨论】:

  • 使用str.replace(i, "\x1c"," ")而不是i.replace("\x1c"," ")的原因是什么?
  • @PaulCornelius - 我不知道,但同意它看起来更好。
  • @SarahMwamlima - 欢迎您!如果我的回答有帮助,请不要忘记 accept 它 - 单击答案旁边的复选标记,将其从灰色切换为已填充。谢谢。
猜你喜欢
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多