2

I am basically writing a simple function in which the user enters a sentence (strng), a letter (letter) and another letter (replace) to replace the first letter with. Here's what I have:

def letter_replace(strng, letter, replace):
    replace = str(replace)
    for char in strng:
        if char == letter.upper() or char == letter.lower():
            strng.replace(char, replace)
            return strng
        else:
            return "Sorry, the letter could not be replaced."

I can't figure out why this won't work. Sorry if it's a completely obvious mistake, I am fairly new to Python. Thanks

4

4 回答 4

6

strings是不可变的,您需要将其分配给一个新变量并返回它。replace()返回一个新字符串,并且不会就地更改它。

>>> def letter_replace(strng, letter, replace):
    replace = str(replace)
    for char in strng:
        if char == letter.upper() or char == letter.lower():
            strng = strng.replace(char, replace)
            return strng   # Or just do return strng.replace(char, replace)
        else:
            return "Sorry, the letter could not be replaced."


>>> letter_replace('abc', 'a', 'f')
'fbc'
于 2013-07-26T16:48:38.363 回答
3
strng.replace(char, replace)

这会进行替换,创建一个新字符串,然后丢弃更改的字符串,因为您没有将其分配给变量。

由于无论如何您都将返回它,因此您可以简单地编写:

return strng.replace(char, replace)
于 2013-07-26T16:49:56.813 回答
0

使用字符串翻译!!!

import string
old_chars = "aeiou"
replace_chars = "!@#$%"
tab = string.maketrans(old_chars,replace_chars)
print "somestring".translate(tab)

哦,没关系...我刚刚读到您只想使用一个字符...

使用 string.replace ...

于 2013-07-26T17:01:04.910 回答
0

您可以使用正则表达式执行此操作:

In [11]: import re

In [12]: def letter_replace(s, l, r):
   ....:     p = re.compile(l, re.IGNORECASE)
   ....:     return p.sub(r, s, 1)
   ....: 

In [13]: letter_replace('AaBbCc', 'a', 'x')
Out[13]: 'xaBbCc'
于 2013-07-26T16:50:55.100 回答