Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (50.2k points)
I want to know the reason behind the immutable nature of string in Python and how can I program without mutable strings?

1 Answer

0 votes
by (107k points)

When you are having string format data, you'll be assured that it stays the same. Assume that you have created one function named Foo in Python as below with a string argument, and would then modify the string; then the Foo's name would suddenly change:

class Foo(object):

    def __init__(self, name):

        self.name = name

name = "Hello"

foo = Foo(name)

name[0] = "J"

If the strings are mutable, then you have to make copies all the time to prevent errors and confusion. 

It also provides the benefit that a single character is no different from a string of length one, so all string operators apply to characters as well.

Now coming to your concern, programming with immutable strings, just treat them as you treat numbers: as values, not as objects. If you want to change the first letter of the name would be

name = "J" + name[1:]

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jun 17, 2020 in Python by Sudhir_1997 (55.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...