DEV Community

Asish kumar sahu
Asish kumar sahu

Posted on

Python Doubt

message = "sea you soon"
message[2] = "e"
print(message)

o/p: TypeError: 'str' object does not support it

In this string I wanted to change particular index can you give some clue how to resolve it

Top comments (3)

Collapse
 
kevteg profile image
Kevin José Hernández González

Hey Asish, in Python string objects are inmutable, you need to create a new string

Collapse
 
asish0sahu profile image
Asish kumar sahu

if i wanted to replace it that is it possible

Collapse
 
evanepio profile image
Evan Porter

Short answer as mentioned by Kevin, is “no”.

The long answer is you can create a new string based on the existing string.

new_message = f"{message[0:2]}e{message[3:]}"
Enter fullscreen mode Exit fullscreen mode

In the above example I used an f-string to make the new string, but it’s not the only option.

The message[0:2] gives you “se” and the message[3:] gives you “ you soon”. These expressions are called slices in Python.