【问题标题】:Replace text in a list with tuples用元组替换列表中的文本
【发布时间】:2019-11-24 15:42:36
【问题描述】:

这是我在这里的第一个问题,我正在学习python并试图解决以下问题:

我使用 CX_oracle 库执行 SQL 查询。 结果以列表的形式返回,其中包含查询返回的所有行的元组。我将它保存在一个名为“数据”的变量中。 下面以一行为例。

[('tuple_item_1','tuple_item_2', 'this\nis\none\nstring\nwith\nlinebrakes')]

我想做的是在初始元组中搜索 '\n' 并将其替换为新元组中的空格字符。我知道元组本身不能被修改。这样做的目的是将其输出到不带换行符的 csv 文件,以便某些工具可以对其进行解释。

非常感谢您的帮助。 先感谢您。

def querydata(): #create function
sql = 'select * from db1' #sql statement
cursor.execute(sql) #cursor
headers = [row[0] for row in cursor.description] #column names saved into variable 'headers'
data = cursor.fetchall() #all returned data saved into variable 'data'
data2 = ["" if s == "\n" else None for s in data]
return data2 

【问题讨论】:

    标签: python list replace tuples


    【解决方案1】:
    >>> data = [('tuple_item_1','tuple_item_2', 'this\nis\none\nstring\nwith\nlinebrakes')]
    >>> data2 = [tuple(item.replace('\n', ' ') for item in row) for row in data]
    >>> data2
    [('tuple_item_1', 'tuple_item_2', 'this is one string with linebrakes')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-03-14
      • 1970-01-01
      相关资源
      最近更新 更多