Python程序查找字符串中所有重复的字符

在本教程中,我们将学习如何在字符串中查找所有重复值。我们可以在Python中以不同的方式进行操作。让我们一一探讨。

我们要编写的程序的目的是查找字符串中存在的重复字符。例如,我们有一个字符串tutorials 指向该程序会将toi 作为输出。用简单的话来说,我们必须找到字符数大于字符串1的字符。让我们来看看。

暂存程序

在不使用任何模块的情况下编写程序。我们可以使用Python的不同方法来实现我们的目标。首先,我们将使用count方法找到字符串的重复字符。让我们首先来看一下过程。

  • 初始化字符串。

  • 初始化一个空列表

  • 遍历字符串。

    • 使用计数方法检查字符频率是否大于一。

If greater than one check whether it's present in the list or not.
If not present append to the list
  • 打印字符

示例

## initializing string
string = "nhooo"
## initializing a list to append all the duplicate characters
duplicates = []
for char in string:
   ## checking whether the character have a duplicate or not
   ## str.count(char) returns the frequency of a char in the str
   if string.count(char) > 1:
   ## appending to the list if it's already not present
   if char not in duplicates:
   duplicates.append(char)
print(*duplicates)

如果运行上面的程序,您将得到以下结果。

输出结果

t o i

现在,我们将找到没有任何方法的字符串重复字符。我们将使用字典数据结构来获取所需的输出。让我们首先来看一下过程。

  • 初始化字符串。

  • 初始化一个空字典

  • 遍历字符串。

    • 检查字典中是否已存在字符

    • 将char的计数初始化为1

Increase the count

示例

## initializing string
string = "nhooo"
## initializing a dictionary
duplicates = {}
for char in string:
   ## checking whether the char is already present in dictionary or not
   if char in duplicates:
      ## increasing count if present
      duplicates[char] += 1
   else:
      ## initializing count to 1 if not present
      duplicates[char] = 1
for key, value in duplicates.items():
   if value > 1:
      print(key, end = " ")
print()

如果您运行上述程序,

输出结果

t o i