Python:.replace 在方法函数中不起作用? [英] Python: .replace doesn't work in method function?

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

问题描述

当我运行这个时:

def Replace(word):
    word.replace('o', 'x')
    return word

print Replace('word')
print 'word'.replace('o', 'x')

我明白了:

word
wxrd

我刚刚开始使用 Python,但我不明白我的输出会有什么不同.任何人都可以澄清吗?我使用的是 2.7.6.

I am just starting to use Python but I don't understand how my outputs would be any different. Can anyone clarify? I'm using 2.7.6.

推荐答案

.replace() 不会就地替换 - 它返回一个新字符串 你应该返回:

.replace() doesn't replace in place - it returns a new string which you should return:

def Replace(word):
    new_word = word.replace('o', 'x')
    return new_word

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

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