Modifying and Deleting Strings
As you already learnt, strings in python are
immutable. That means, once you define a string modifications or deletion is
not allowed. If you want to modify the string, a new string value can be assign
to the existing string variable.
Example
>>>str1="How are
you"
>>>str1[0]="A"
Traceback (most recent call
last):
File "<pyshell#1>",
line 1, in <module>
str1[0]="A"
TypeError: 'str' object does not
support item assignment
In the above example, string variable str1 has
been assigned with the string “How are you” in statement 1. In the next
statement, we try to update the first character of the string with character
‘A’. But python will not allow the update and it shows a TypeError.
To overcome this problem, you can define a new
string value to the existing string variable. Python completely overwrite new
string on the existing string.
Example
>>>str1="How are
you"
>>>print (str1)
How are you
>>>str1="How about
you"
>>>print (str1)
How about you
Usually python does not support any
modification in its strings. But, it provides a function replace() to change
all occurrences of a particular character in a string.
General formate of replace function:
replace(“char1”, “char2”)
The replace function replaces all occurrences
of char1 with char2.
Example
>>>str1="How are
you"
>>>print (str1)
How are you
>>>print
(str1.replace("o", "e"))
Hew are yeu
Similar as modification, python will not allow
deleting a particular character in a string.
Whereas you can remove entire string variable
using del command.
Example: Code lines to delete a particular
character in a string:
>>>str1="How are you"
>>>del str1[2]
Traceback (most recent call
last):
File
"<pyshell#7>", line 1, in <module>
del str1[2]
TypeError: 'str' object doesn't
support item deletion
Example: Code lines to delete a string variable
>>>str1="How about
you"
>>>print (str1)
How about you
>>>del str1
>>>print (str1)
Traceback (most recent call
last):
File
"<pyshell#14>", line 1, in <module>
print (str1)
NameError: name 'str1' is not defined
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2026 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.