查找字符串中的第二个重复符号

2024-04-19 15:12:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,例如210132。如何在字符串中找到第二个重复符号(在本例中是2)?你知道吗


Tags: 字符串符号本例
2条回答

最后我解决了我的任务,感谢@John Gordon使用枚举函数的想法

print('Enter string')    
while 1 > 0:
    string = input()
    if string == 'stop':
        break
    result = list()
    for pos, ch in enumerate(string[1:]):
        if ch in string[:pos+1]:
            result.append(ch)
    if len(result) < 2:
        print('No second repeating character.Enter another string')
        continue
    print(result[1],'is the second repeating character')

从第二个字符开始遍历字符串中的每个字符(因为第一个字符不能重复),跟踪当前位置。你知道吗

在该位置之前的字符串部分中搜索该字符。你知道吗

for pos, ch in enumerate(mystring[1:]):
    if ch in mystring[:pos+1]:
        print ch

相关问题 更多 >