迭代一个字符串并替换python中的元素 [英] Iterating a string and replacing an element in python

查看:227
本文介绍了迭代一个字符串并替换python中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试搜索两个字符串以查找匹配元素。如果字符串有两个共同位于不同位置的元素,我想让'guess'字符串中的元素成为COW。如果字符串在同一位置有两个元素,则该元素为BULL。

I am attempting to search through two strings looking for matching elements. If the strings have two elements in common that are in different positions, I want to make that element in the 'guess' string a COW. If the strings have two elements in the same position, the element is a BULL.

这是我所拥有的:

        if index(number,i) in guess and not index(guess,i) == index(guess,i):
            replace(index(guess,i),'COW')

        if index(guess,i) == index(number,i):
            replace(index(guess,i),'BULL')

我不确定我是否正确使用索引。

I'm not sure if I'm using index correctly.

推荐答案

首先,你需要使用 index() replace()作为字符串方法,如Martijn在评论中所说。

First off, you need to be using index() and replace() as string methods, like Martijn said in a comment.

这就是这样: guess.index(i)找到的索引i 字符串 guess

This would be like so: guess.index(i) to find the index of i in the string guess.

您可能想要查看 find()与<$ c $相同c> index()但在找不到子字符串时不会引发异常。

You might want to check out find() which will do the same as index() but won't raise an exception when the substring is not found.

另请注意你看到 index()的结果是否在字符串 guess 中。这是一个错误,因为整数不能在字符串中! index()返回一个整数!

Also note that you are seeing if the result of index() is in the string guess. That is an error, since an integer cannot be in a string! index() returns an integer!

然后考虑你说明 ...而不是guess.index(i)== guess.index(i):(我修复了索引代码)这是没有意义的,因为当然他们是平等的!它们是一样的!

Then consider that you are stating ... and not guess.index(i) == guess.index(i): (I fixed the index code) which makes no sense, since of course they are equal! They are the same thing!

最后,你错误地使用替换
来自文档 replace 将一个字符串作为第一个参数 - 而不是索引!尝试使用它如下: guess = guess.replace(i,'BULL')。这将改变 guess 所有出现的 i 替换为字符串'BULL'

Lastly, you are using replace incorrectly. From the documentation, replace takes a string as the first argument - not an index! Try using it like so: guess = guess.replace(i, 'BULL'). That will change guess to have all occurrences of i replaced by the string 'BULL'.

我这里并不关心你的实际算法,只是你的基本错误。

I wasn't concerned with you actual algorithm here, but just your basic errors.

这篇关于迭代一个字符串并替换python中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆