Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify a single character in a string, in Python?

Tags:

python

string

How do I modify a single character in a string, in Python? Something like:

 a = "hello"
 a[2] = "m"

'str' object does not support item assignment.

like image 595
Shane Avatar asked Oct 05 '10 05:10

Shane


People also ask

How do you change part of a string in Python?

In Python, the . replace() method and the re. sub() function are often used to clean up text by removing strings or substrings or replacing them.

Can you directly change the individual characters of a string?

String are immutable in Java. You can't change them. You need to create a new string with the character replaced.

Can we modify a string value in Python?

Python strings are immutable (i.e. they can't be modified).


2 Answers

Strings are immutable in Python. You can use a list of characters instead:

a = list("hello")

When you want to display the result use ''.join(a):

a[2] = 'm'
print ''.join(a)
like image 115
Mark Byers Avatar answered Oct 08 '22 12:10

Mark Byers


In python, string are immutable. If you want to change a single character, you'll have to use slicing:

a = "hello"
a = a[:2] + "m" + a[3:]
like image 22
JoshD Avatar answered Oct 08 '22 12:10

JoshD