How to remove only one of a certain character from a string that appears multiple times in Python 3
本问题已经有最佳答案,请猛点这里访问。
我想知道如何从一个出现多次的字符串中只删除某个字符。
例子:
1 2 3 4 | >>>x = 'a,b,c,d' >>>x = x.someremovingfunction(',', 3) >>>print(x) 'a,b,cd' |
如果有人能帮忙,我将不胜感激!
按要删除的字符拆分原始字符串。然后重新组装违规字符前面和后面的部分,并重新组合这些部分:
1 2 3 4 5 6 | 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' |
假设参数
1 2 3 4 5 6 7 8 9 | 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 |
使用实例:
1 | print someremovingfunction('a,b,c,d', ',', 3) |
这可能有帮助
1 2 3 | >>> x = 'a,b,c,d' >>> ''.join(x.split(',')) 'abcd' |