如果你想去重字符串并保持原始顺序,可以使用列表来存储不重复的字符,并在添加字符到列表时检查是否已经存在。以下是一个实现的示例:
def remove_duplicates_and_preserve_order(input_string):
unique_chars = []
for char in input_string:
if char not in unique_chars:
unique_chars.append(char)
result_string = ''.join(unique_chars)
return result_string
input_string = "hello"
result = remove_duplicates_and_preserve_order(input_string)
print(result) # 输出 "helo"
在这个示例中,unique_chars
列表用于存储不重复的字符。在遍历原始字符串时,如果字符尚未在 unique_chars
中出现,就将它添加到列表中。最后,使用 join()
方法将列表中的字符连接成字符串。
这种方法会保持原始顺序,并移除重复的字符,得到一个去重后的字符串。