Sunday, 24 March 2019

Deletion and Updating in Python String

In python you cannot delete or update any particular character or a sequence of characters. In simple words, deletion and updating of characters is not possible in a defined string of Python. As python strings are immutable. Hence they can't be changed once defined. But you can assign the same identifier to a new string. But what if you want to delete that previous defined string. In that case you can use the 'del' keyword. This keyword will delete the previously defined string and will throw a not defined error if you try to print or access the deleted string. Let's take some examples to see the deletion and updating operations on a python string.

Updating a single character:


#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")
print(string)
print("\n")

#updating a single character
string[2]='h'
print("\n\nPrinting the updated string:\n")
print(string)


Output:

 

Updating an entire string:


#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")
print(string)
print("\n")

#updating a single character
string = 'hello'
print("\n\nPrinting the updated string:\n")
print(string)

Output:

 

Deletion of a single character:


#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")
print(string)
print("\n")

#deleting the single character
del string[1]
print("\n\nPrinting the updated string:\n")
print(string)

Output:


 

Deleting an entire String:


#define a string

string = 'Hello World'
print("\n\nPrinting the original string:")
print(string)
print("\n")

#deleting the single character
del string
print("\n\nPrinting the updated string:\n")
print(string)

Output:

 


EmoticonEmoticon