繁体   English   中英

我想摆脱所有像 [(' 这样的特殊字符,我真的陷入了如何

[英]I want to get rid of all the special characters like [(' and im really stuck in how to

def trackItems():
    cursor.execute("SELECT ItemsBought, COUNT(*) FROM Purchase GROUP BY ItemsBought")
    stock = []
    Graphs = cursor.fetchall()
    print(Graphs)
    separator = " "
    f = open("Stock.txt", "w")

    values = ','.join([str(i) for i in Graphs])
    f.write(values)

Output

('不要', 1),('我的', 2),('请', 2)

我怎样才能摆脱左括号和右括号以及所有引号。 如果有人可以提供帮助,将不胜感激

您可以使用 str.replace(substring, "") 将字符串中的子字符串替换为 "" (因此它将删除它),例如

    "(abcd(.ad".replace("(", "") #output: abcd.ad

然后你可以把这个字符串写到文件中。 代码:

    def trackItems():
        cursor.execute("SELECT ItemsBought, COUNT(*) FROM Purchase GROUP BY ItemsBought")
        stock = []
        Graphs = cursor.fetchall()
        print(Graphs)
        separator = " "
        f = open("Stock.txt", "w")
        values = ','.join([str(i) for i in Graphs]).replace("(", "").replace(")", "").replace("'", "")
        f.write(values)

与其将其视为特殊字符的问题,不如将其视为将子序列(元组、行)的序列(列表)扁平化为单个元素的列表,然后可以将其joined起来。

您可以使用for循环执行此操作:

 >>> flattened = []
>>> for row in Graphs:
...     flattened.extend(row)
... 
>>> flattened
['DONT', 1, 'MY', 2, 'PLEASE', 2]

但列表理解更惯用

>>> Graphs = [('DONT', 1),('MY', 2),('PLEASE', 2)]
>>> values = ','.join([str(i) for j in Graphs for i in j])
>>> print(values)
DONT,1,MY,2,PLEASE,2

暂无
暂无

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

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