+ 1
How to replace a letter into another in a string using module "string"?
in python2 i can simply type like import string s = "aaaaaaa" string.replace(s, 'a', 'b') but it can't work in python3. so how can i realize it in python3
6 Answers
+ 1
s = 'aaaaaaa'
s = s.replace('a', 'b')
or you can define new function and use like in Python2:
s = 'aaaaaaa'
replace = lambda x, y, z: x.replace(y, z)
s = replace(s, 'a', 'b')
or define class string:
class string:
def replace(x, y, z):
return x.replace(y, z)
s = 'aaaaaaa'
s = string.replace(s, 'a', 'b')
but if you needs more powerfull method of replasing, use sub from module re:
from re import sub
s = 'aaaaaaa'
pattern = r"a"
s = s.sub(pattern, 'b')
+ 1
re on:
<<
i tried it but still doesn't work
...
t.replace('k', 'h')
print(t)
>>
try like this:
t = t.replace('k', 'h')
print(t)
or:
print( t.replace('k', 'h'))
0
In python 3 you use it like this:
s.replace('a', 'b') or 'aaaaa'.replace('a', 'b')
0
i tried it but still doesn't work:
import string
t = "kkkkkkkkk"
t.replace('k', 'h')
print (t)
the letters can't be replaced, why?
0
cool! thx!
- 1
well, the method does not replace in place. It returns a new string. Try:
newT = t.replace('k','h')
print(newT)