replace string characters in python

How to Change One Character in Python String

Python strings are commonly used by developers to store text and other information. They are very useful and feature-rich. Often while working with strings, you may need to replace or change one or more characters in python string. When we try to do this we may end up getting error messages, and be surprised. In this article, we will learn why this happens and how to change one character in python string.

How to Change One Character in Python String

Let us say you have the following python string.

text = 'hello world'

Let us you want to change the second letter of this string from ‘e’ to ‘f’. Typically, people treat python strings as an array and try to change by accessing the character using index and using assignment operator to set new value to it as shown below.

text[1] = 'f'

When they do this they get the following error.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

This approach works in other scripting languages such as JavaScript but does not work in Python. This error happens because python strings are immutable, that is, they cannot be modified. You can assign a new value to your string variable but not change its individual characters directly.

text = 'hello1'

Then how do we change specific characters in python string? The solution is to first convert a string to a list of characters, then update the specific character you want, and then convert the list back to string. We convert a string to list using list() function. We use indexes to access the specific character we want to change and use assignment operator to replace it. We finally use join() function to convert list into string. Here is an example where we replace ‘w’ with ‘t’ in ‘Hello world’.

>>> text = 'Hello world'
>>> s = list(text) # or list('Hello world')
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
>>> s[6] = 't'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 't', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello torld'

You can use this approach to change multiple characters in python string. In this article, we have learnt how to change specific characters in python string.

Also read:

How to Permanently Add Directory to Python Path
How to Install Python Package with .whl file
How to Convert JSON to Pandas Dataframe
How to Write List to File in Python
How to Fix Invalid Use of Group Function

Leave a Reply

Your email address will not be published. Required fields are marked *