python - 如何删除字符串中第一次出现的字符之后的每次出现

标签 python

test = "abcdefbdbob"

如何删除第一个 b 之后出现的所有“b”?

最佳答案

您可以将字符添加到结果列表中,然后将其重新连接到末尾(这会删除第一个字符之后的所有重复字符),例如:

In []:
result = []
for c in test:
    if c in result:
        continue
    result.append(c)

''.join(result)

Out[]:
'abcdefo'

您可以在列表理解中执行此操作,但使用帮助器 set() 有点麻烦,例如:

In []:
seen = set()
''.join(seen.add(c) or c for c in test if c not in seen)

Out[]:
'abcdefo'

关于python - 如何删除字符串中第一次出现的字符之后的每次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60697941/

相关文章:

python - Instagram 客户端错误

python - 类型错误 : can only concatenate list (not "tuple") to list ((Python))

python - 还是关于python文件操作

python - Pandas 中每一列的曲线拟合 + 外推值

python - 使用 python 从 MYSQL 数据库中显示随机抽认卡

Python 将字典转换为数据框失败

python - Tensorflow 2.0 结合 CNN + LSTM

python - 根据可能重复的管道分隔列制作新的 Pandas 列

Python程序具有来自同一脚本的多个具有不同端口号的套接字?

python - 在关闭信号时在 python 脚本中运行代码