Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

String — Not able to modify string

I have the following code:

welcome = 'Welcome to my house'
welcome[2] = 'd'
print(welcome)

But it always gives an error.
Can anyone guide me to solve the mistake?
I am very new to programming, and I am sorry if my question is silly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

String data type is immutable. Therefore, you cannot explicitly modify a string.
You can split all the characters to form a list, change the character, then form the string again.

def spliter(string):
    return [char for char in string]
     
s = "Welcome to my house"
l = spliter(s)
l[2] = 'd'
welcome = ''
for i in l:
    welcome += i
print(welcome)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading