简体   繁体   中英

Using str.replace to replace letters in a string at different placeholders of the string

I have a problem that I am working on. The goal of the problem is to take the string placeholder i . If i is an even placeholder, replace the letter at i with the letter at i -1 . If the i place holder is odd, then replace the letter i with the letter at i +1 .

Here is my code so far:

def easyCrypto (s):
    for i in range (0,len(s)-1):
        if i % 2 == 0:
            str(s).replace(i,((i-1)))
        if i % 2 != 0:
            str(s).replace(i,((i+2)))
    print (s)

My error:

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    easyCrypto('abc')
  File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
    str(s).replace(i,((i-1)))
TypeError: Can't convert 'int' object to str implicitly

update!!

New code based on answers:

def easyCrypto (s):
    for i in range (0,len(s)-1):
        if i % 2 == 0:
            s =  str(s).replace(s(i),(s(i-1)))
        else:
            s = s.replace(s(i), s(i + 1))
    print (s)

However I still have the following errors:

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    easyCrypto('abc')
  File "C:/Python/cjakobhomework7.py", line 4, in easyCrypto
    s =  str(s).replace(s(i),(s(i-1)))
TypeError: 'str' object is not callable

Any ideas? thank you

使用s[i]代替s(i) ,其他索引也是如此。

There are two things here:

  1. str.replace does not automatically stringify its arguments. You need to manually convert them into strings. Remember that: "Explicit is better than implicit."

  2. str.replace does not work in-place because strings are immutable in Python. You need to reassign s to the new string object returned by str.replace .

Your code should be:

s = s.replace(str(i), str(i-1))

Also, you can replace if i % 2 != 0: with else: since the condition of the second if-statement can only be true if the first is false:

if i % 2 == 0:
   s = s.replace(str(i), str(i-1))
else:
   s = s.replace(str(i), str(i+1))

Regarding your edited question, you are trying to call the string s as a function by placing parenthesis after it. You need to use square brackets to index the string:

>>> 'abcde'[0]
'a'
>>> 'abcde'[3]
'd'
>>>

In your case it would be:

s =  s.replace(s[i], s[i-1])

As a general rule of thumb, parenthesis (...) are for calling functions while square brackets [...] are for indexing sequences/containers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM