0

How to replace a character in a Python string?

Exemple: I have a string x = "hey" and I want to replace de 2nd character with "a" to turn x into "hay", is there any function that does it? obs: I'm using Python 3

9th Sep 2018, 1:03 AM
salgueiro lutador
salgueiro lutador - avatar
2 Respostas
+ 3
Function replace does it: https://www.tutorialspoint.com/JUMP_LINK__&&__python__&&__JUMP_LINK/string_replace.htm In this case: a = "hey" print (a.replace('e','a'))
9th Sep 2018, 1:33 AM
Ruben Rodriguez
Ruben Rodriguez - avatar
+ 3
Note that .replace will replace every 'e' in x with an 'a'. If x is 'heyes' and you use x.replace('e', 'a'), it will be 'hayas' afterwards. If you only want to replace the first 'e' in the string, use x.replace('e', 'a', 1) instead. If you want to replace the second character no matter what (even if it's not an 'e'), you'll probably need something more complex like y = x[:1] + 'a' + x[2:].
9th Sep 2018, 6:23 AM
Anna
Anna - avatar