string immutable python examples

Python String Immutability with Examples

In this tutorial you will learn about Python String immutability. In Python string objects are made immutable so that programmers cannot modify the contents of the object even by mistake.

Python String Immutability – Examples

string immutable python examples

Python strings are not mutable. It means that you cannot use indexing to modify the individual characters or elements of a string (strings in Python are ordered sequence of characters).

Let’s try to understand better with the following example.

Create a string object.

>>> name = "John"

Next, let’s try to use string index to modify a character in the given string i.e., try to modify the first character of the string.

>>> name[0] = "K"
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-108-daf616b38898> in <module>
----> 1 name[0] = "K"

TypeError: 'str' object does not support item assignment

Therefore, you cannot use indexing to alter the individual elements of a string. Hence strings in Python are immutable.

In the next section you will learn how to modify strings in Python.

How to modify strings in Python ?

Strings are immutable. But you can accomplish strings modification in Python by generating a copy of original.

Here are some examples that shows how to modify string in Python.

>>> name = "John"

>>> last_characters = name[1:]

>>> last_characters
'ohn'

>>> 'K' + last_characters
'Kohn'

>>> x = 'Hello World'

>>> x = x + ", welcome to our paradise"

>>> x
'Hello World, welcome to our paradise'

>>> ch = 'y"

>>> ch * 10
'yyyyyyyyyy'

>>> '5' + '4'
'54'

Also, you can use String methods to modify strings in Python as shown in the examples below.

>>> x = 'Hello World'

>>> x.upper()
'HELLO WORLD'

>>> x
'Hello World'

>>> x.lower()
'hello world'

>>> x.replace('H', 'F')
'Fello World'

>>> x[:0] +'F'+ x[1:]
'Fello World'

That’s it. Basically, you had learnt why Python strings are called immutable and how to accomplish changing strings by generating copy of the original string in Python. Also, learnt some strings properties and methods to achieve the same.

Hope it helped πŸ™‚

You’ll also like:

References

Β 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments