Reputation: 463
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
Upvotes: 2
Views: 7620
Reputation: 113940
use string translate!!!
import string
old_chars = "aeiou"
replace_chars = "!@#$%"
tab = string.maketrans(old_chars,replace_chars)
print "somestring".translate(tab)
oh nevermind... I just read you only want to use one character ...
use string.replace ...
Upvotes: 0
Reputation: 33651
You could do this using regex:
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'
Upvotes: 0
Reputation: 184091
strng.replace(char, replace)
This does the replacement, creating a new string, and then throws away the changed string because you don't assign it to a variable.
Since you're just going to return it anyway, you can simply write:
return strng.replace(char, replace)
Upvotes: 3
Reputation: 34493
strings
are immutable, you need to assign it to a new variable and return that. replace()
returns a new string and does not change it in place.
>>> 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'
Upvotes: 6