How to replace a letter into another in a string using module "string"? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 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

17th Mar 2017, 3:53 PM
biohawking
6 ответов
+ 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')
21st Mar 2017, 12:22 AM
learner
+ 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'))
21st Mar 2017, 12:29 AM
learner
0
In python 3 you use it like this: s.replace('a', 'b') or 'aaaaa'.replace('a', 'b')
17th Mar 2017, 6:10 PM
hdo
hdo - avatar
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?
18th Mar 2017, 2:30 AM
biohawking
0
cool! thx!
18th Mar 2017, 6:57 AM
biohawking
- 1
well, the method does not replace in place. It returns a new string. Try: newT = t.replace('k','h') print(newT)
18th Mar 2017, 2:45 AM
hdo
hdo - avatar