string: welcome Subscript [ - ] : e Subscript [ - ] : m Subscript [ - ] : o Subscript [ - ] : c Subscript [ - ] : l Subscript [ - ] : e Subscript [ - ] : w Example : Program to access each character with its negative subscript of a giving string . 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. However, we can replace the existing string entirely with the new string.
12th Computer Chapter - - Strings and String Manipulation >>> str1="How are you" >>> str1[ ]="A" Traceback (most recent call last): File "<pyshell# >", line , in <module> str1[ ]="A" TypeError: 'str' object does not support item assignment Example In the above example, string variable str1 has been assigned with the string “How are you” in statement . 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. >>> str1="How are you" >>> print (str1) How are you >>> str1="How about you" >>> print (str1) How about you Example Usually python does not support any modification in its strings. But, it provides a function replace() to temporarily change all occurrences of a particular character in a string. The changes done through replace () does not affect the original string.
General formate of replace function: replace(“char1”, “char2”) The replace function replaces all occurrences of char1 with char2. >>> str1="How are you" >>> print (str1) How are you >>> print (str1.replace("o", "e")) Hew are yeu Example Similar as modification, python will not allow deleting a particular character in a string. Whereas you can remove entire string variable using del command. 12th Computer Chapter - - >>> str1="How are you" >>> del str1[ ] Traceback (most