str.replace 在函数内不起作用 [英] str.replace won't work within a function

查看:41
本文介绍了str.replace 在函数内不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个函数没有返回替换的结果?

Why is this function not returning the result of the replace?

def replacechar(str):
    str.replace("č","c")
    str.replace("a","y")
    return str
p= "abcdč"
replacechar(p)
print(p) 

输出:

abcdč

推荐答案

str.replace 不是就地操作.它返回一个字符串.好消息是您的函数只需少量修改即可工作.

str.replace is not an inplace operation. It returns a string. The good news is that your function will work with minimal modification.

def replacechar(string):
    return string.replace("č","c").replace("a","y")

接下来,您需要将返回值分配回 p:

Next, you will need to assign the return value back to p:

p = replacechar(p)

另外,不要使用 str 来命名一个对象,因为你已经有了使用这个名字的东西.

Also, don't use str to name an object because you already have something with that name.

或者,您是否考虑过 str.translate?

Alternatively, have you considered str.translate?

_TAB = str.maketrans({'č' : 'c', 'a' : 'y'})
def replacechar(string):
    return string.translate(_TAB)

这篇关于str.replace 在函数内不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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