【问题标题】:Replace parts of string in sqlite3替换sqlite3中的部分字符串
【发布时间】:2016-01-25 18:36:32
【问题描述】:

我想替换字符串中的零件信息。

例如从+1-2024561111+1-202***1111

我找到了一个查询REPLICATE,它可以实现我想要的。但是,它似乎在 sqlite3 中不可用。

而且sqlite中的REPLACE只能替换某些特定的字符串。我需要的是替换某些位置的字符串。一个字母替换一个 '*' ;替换后它们需要具有相同的长度。

即使是 Excel 也可以使用 REPLACE(old_text, start_num, num_chars, new_text) 轻松完成此操作。有没有办法解决这个问题?顺便说一句,我在 python 中使用 sqlite3。用python写的解决方案也是可以的。

【问题讨论】:

  • 那么不同的子串要区别对待吗?为什么不能使用substr()

标签: python replace sqlite replicate


【解决方案1】:
REPLACE(old_text, start_num, num_chars, new_text)

应该与

相同
SUBSTR(old_str, 1, start_num - 1) || new_text || SUBSTR(old_str, start_num + LENGTH(new_text))

【讨论】:

    【解决方案2】:

    在 sqlite 中使用 substr 和替换

    我终于用substr(x,y,z)y获取第一个z字符(我设置了1以从原始字符串的开头开始)。

    然后使用|| 连接两个字符串。与@Hugh Bothwell 提供的答案略有不同。

    ||之后,我使用replace(substr(quote(zeroblob((Y + 1) / 2)), 3, Y), '0', '*')将字符串填充到length Y。一开始有点难理解。This website有更多的信息给你。

    我需要在第 5 个字符后屏蔽我的字符串,因此我不需要在 replace 语句后面附加任何内容。如果需要,只需添加另一个 || 并使用 substr()

    简而言之,我所做的是:+1-2024561111(原始字符串)

    • substr() ➜ +1-202456
    • || ➜ 追加另一个字符串
    • replace 语句 ➜ 将字符串填充到一定长度 ➜ +1-202456****


    另一种解决方案:在python中

    像这样在sqlite3 in python打印数据库是正常的:

    for row in c.execute('SELECT * FROM stocks ORDER BY price'):
            print row
    

    我添加了一个if-else 语句并使用ljust 来做我想做的事情。

    下面是一个示例:

    -- row[0]: the first filed in table, here means numbers
    
        if len(row[0])>=9:
                newNum=row[0][0:10].ljust(len(row[0]),'*')
                            #^^^^^^ to get first 9 chars in row[0]
    
        # ljust fill in '*' from 10th char to the length of row[0]
    
        print(newNum) # use newNum instead of row[0]
    

    【讨论】:

      猜你喜欢
      • 2016-12-17
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 2021-03-25
      • 1970-01-01
      相关资源
      最近更新 更多