python字符串查找重复项,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的计数初始化为1Increase 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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值