Python Tutorial

Delete or Change a String in Python with examples

Table of Contents

  • How to Delete or Change a String in Python?
  • Remove Whitespace
  • Replace String

How to Delete or Change a String in Python?

You can't edit or modify strings as they are unchangeable. What this implies is that once you have allocated the elements to a string, you can't make changes to them. You can only reassign the same name to different strings. 

Example

my_string = 'wscubetech'

my_string[5] = 'a'

my_string = 'Python'

my_string
'Python'

A character in a string cannot be erased or removed. On the other hand, the del keyword can be used to totally remove a string.

>>> del my_string[1]

...

TypeError: 'str' object doesn't support item deletion

>>> del my_string

>>> my_string

...

NameError: name 'my_string' is not defined

Remove Whitespace

The space after and/or before the actual text is known as whitespace, and it's fairly common to desire to get rid of it.

Code:

a = " Wscube  "

print(a.strip())

Output:

Wscube

Replace String

The replace() function swaps out one string for another:

Code:

a = "wscube"

print(a.replace("w", "j"))

Output:

jscube
Did you find this article helpful?