【问题标题】:How to remove only one of a certain character from a string that appears multiple times in Python 3 [duplicate]如何从 Python 3 中多次出现的字符串中仅删除某个字符中的一个 [重复]
【发布时间】:2017-07-15 19:35:00
【问题描述】:

我试图弄清楚如何从多次出现的字符串中删除某个字符。

例子:

>>>x = 'a,b,c,d'
>>>x = x.someremovingfunction(',', 3)
>>>print(x)
'a,b,cd'

如果有人能提供帮助,将不胜感激!

【问题讨论】:

  • 3 在这里代表什么?
  • 我猜3 表示这个字符的第三次出现?
  • @vascowhite 我不认为这是重复的:第 n 个字符 of a kind 和中间字符 of a string 是两个非常不同的东西。

标签: python string


【解决方案1】:

这可能会有所帮助

>>> x = 'a,b,c,d'
>>> ''.join(x.split(','))
'abcd'

【讨论】:

  • 这不是 OP 所要求的:您要删除所有符号,而不是其中一个。
【解决方案2】:

假设参数3 表示有问题的字符的出现,您可以迭代字符串并计数。当您发现出现时,只需创建一个没有它的新字符串。

def someremovingfunction(text, char, occurence):
    pos = 0
    for i in text:
        pos += 1
        if i == char:
            occurence -= 1
            if not occurence:
                return text[:pos-1] + text[pos:]
    return text

使用示例:

 print someremovingfunction('a,b,c,d', ',', 3)

【讨论】:

    【解决方案3】:

    按要删除的字符拆分原始字符串。然后重新组装冒犯角色前面和后面的零件,然后重新组合零件:

    def remove_nth(text, separator, position):
        parts = text.split(separator)
        return separator.join(parts[:position]) + separator.join(parts[position:])
    
    remove_nth(x,",",3)
    # 'a,b,cd'
    

    【讨论】:

      猜你喜欢
      • 2021-04-21
      • 2021-01-23
      • 2016-10-06
      • 1970-01-01
      • 2020-06-16
      • 2019-04-23
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多