简体   繁体   English

在python中替换字符串中的字符

[英]replacing a character in a string in python

I am trying to replace a character in a string using python.我正在尝试使用 python 替换字符串中的字符。 I am using a function called find_chr to find the location of the character that needs to be replaced.我正在使用一个名为 find_chr 的函数来查找需要替换的字符的位置。

def main():
    s='IS GOING GO'
    x='N'
    y='a'

    rep_chr(s,x,y)
def find_chr(s,char):
    i=0
    for ch in s:
        if ch==char:
            return (i)
            break        
        i+=1
    return -1
def rep_chr(s1,s2,s3):
    return print(s1==s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):])


main()

My problem is that instead of getting the new string, the function is returning 'False'.我的问题是,该函数没有获取新字符串,而是返回 'False'。 I would appreciate any pointer to get the replaced string.我将不胜感激任何指针来获取替换的字符串。

change改变

return print(s1==s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):])

to

return s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):]

and print the result in your main :并在您的main打印结果:

print(rep_chr(s,x,y))

There is an inbuilt function:有一个内置函数:

string.replace(old, new, count)

this returns a modified copy这将返回一个修改后的副本

count is optional and is the number of times to replace - if it is set to 2 it will replace the first two occurrences. count 是可选的,是替换的次数 - 如果设置为 2,它将替换前两次出现。

string = 'abc abc abc def'
string.replace('abc','xyz',2)

returns返回

'xyz xyz abc def'

The problem is in your print statement inside rep_chr function.问题printrep_chr函数内的print语句中。

s1==s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):]

The above statement means is s1 equal to s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):] ?上面的语句意味着s1等于s1[0:find_chr(s1,s2)]+s3+s1[(find_chr(s1,s2)+1):] which is false and that's why you are getting False as output.这是错误的,这就是为什么您将 False 作为输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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