Replace a character in string using python
String in python is immutable object. Immutable object’s value can not be changed. In case of replacing character of a string , It create a new string after replacing the characters.
Here is what you are looking for :
For Example, replacing “H” with “Y” in “Hello World” returns “Yello World”
2 ways to replace characters in string
Using replace()
1
2
3
4
5
|
phrase = "Hello World"
phrase = pharse.replace( "H" , "Y" );
print(phrase)
|
output:
Yello World
Using list()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
phrase = "Hello World"
converted_list = list(phrase)
# replacing H with Y
converted_list[0] = "Y"
phrase = "".join(converted_list)
print(phrase)
# replacing W with H
converted_list[6] = "H"
phrase = "".join(converted_list)
print(phrase)
|
Output
Yello World
Yello Horld
Sharing is caring!