python - 如何在 Python 3 中查找字符串中的重复项?

标签 python python-3.x string python-3.6

我的目标是找到字符串中的重复字符,并用其他值替换这些唯一和非唯一元素,并将这些其他值放入另一个字符串中。

我使用了计数器,但这是我到目前为止得到的:

from collections import Counter

def duplicate_encode(word):
    word = word
    final_result = ""
    dict_input = Counter(word)
    print(dict_input)
    print(dict_input.items())
    for key in dict_input:
        x = int(dict_input[key])
        print("this is key" + "\t" + key)
        print(x)
        if x == 1:
            final_result += "("
        elif x != 1:
            final_result += ")"
    print("'" + final_result + "'")

duplicate_encode("binaryy")

输出:

'((((()'

例如,对于 "binaryy" ,输出应为 '((((())',而不是 '((((()'.

此外,有没有比 print("'"+ Final_result + "'") 更好的方法来打印字符串

最佳答案

您的循环不应结束for key in dict_input:。这仅在您的示例中仅凭运气才起作用,因为 A) 字典在 Python 3.6+ 中是排序的,并且 B) 您只有一个重复项范围。循环应该对字符串中的实际字符进行编码:

final_result = ''
for c in word:
    final_result += '(' if dict_input[c] == 1 else ')'

您可以(并且可能应该)将其缩短为

final_result = ''.join('(' if dict_input[c] == 1 else ')' for c in word)

要打印带有引号的字符串,只需使用 repr。直接:

print(repr(final_result))

或使用格式:

print(f'{final_result!r}')

关于python - 如何在 Python 3 中查找字符串中的重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57118070/

相关文章:

python - 使用 Pandas 从文本文件中提取标题数据

python - 将上三角形条目的平面列表复制到完整矩阵?

python - OS X 上的 "-bash: python2: command not found"

python - 拦截python的 `print`语句并在GUI中显示

python - 斐波那契特定数字生成器 python

python - 给 Pandas 细胞赋值的最快方法

Python3编译的应用程序通过zip减少大小?

c++ - 将不同的变量分配给来自 cin C++ 的输入

c# - 试图提取字符串中间的代码

c - 需要帮助将二进制数转换为 C 中的字符串