我的目标是找到字符串中的重复字符,并用其他值替换这些唯一和非唯一元素,并将这些其他值放入另一个字符串中。
我使用了计数器
,但这是我到目前为止得到的:
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/