In Python All Fundamental Datatypes Are Immutable Why In String Replace() Function Works? [closed]

Solution for In Python All Fundamental Datatypes Are Immutable Why In String Replace() Function Works? [closed]
is Given Below:

As we all know that All fundamental datatypes in python are immutable and we can’t change anything in them,

If I try to replace something in fundamental data types I will definitely get an error. Take an example from this;

#TRYING TO REPLACE AN INTEGER FROM A VARIABLE.

num=123456789

1=78

print(num)

OUTPUT:

File "D:myPractice.pysideRun.py", line 2
    1=78

    ^
SyntaxError: cannot assign to literal

If fundamental data types are immutable, then why is the string has replace() inbuilt function.

**#REPLACING A OLD STRING WITH A NEW STRING**

s="Jimmy is a student of CS and Jimmy is a boy "

print(id(s))

print(s.replace("CS","SE"))

print(id(s))

In this, both of print() statements that have ID argument are giving the same output that is the same address.

**MY QUESTIONS ARE**
  1. If the string data type is immutable then why it has ‘replace()’ function?

  2. If a new object is created due to ‘replace()’ function then why new and old string has the same ID?

str.replace(...) returns a modified copy of the given string. This method doesn’t mutate your “s” variable.

s = "Jimmy is a student of CS and Jimmy is a boy "
s1 = s.replace("CS","SE")
print(id(s))
print(id(s1))

# your script did nothing but printed ids
# in this case s1 contains modified copy of string "s"
# script will print different ids