python替换字符串元素_迭代一个字符串并替换python中的元素

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.

Here is what I have:

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.

解决方案

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

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

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.

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!

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!

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值