Solved

Change one character in a string. Easiest way

Posted on 2009-05-05
2
847 Views
Last Modified: 2012-05-06
Hi,

I have this list:

list = ['hellolotomao', 4]

want to change list[0][-1] (which now equals 'o')  to 'Z'

if i do,
list[0][-1] = 'Z'
'str' object does not support assignment???

any easy way to do this?
0
Comment
Question by:dfernan
2 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24310695
Strings are "immutable", which means they can not be changed inplace. You must replace the string with the new version of the string.
list[0] = list[0][:-1]+'Z'

Open in new window

0
 
LVL 2

Accepted Solution

by:
jdevera earned 250 total points
ID: 24312308
You can also use a more generic function for this. But always bear in mind that, as cxr explained, you are not actually changing the same string you had, you are creating a new one.
def change_char(string, index, character):
    if index == -1:
        return string[:index] + character
    else:
        return string[:index] + character + string[index+1:]
 
# some tests:
s="abcdef"
print change_char(s, -1, 'x')
# abcdex
print change_char(s, -2, 'y')
# abcdyf
print change_char(s,  1, 'z')
# azcdef
 
# So you can do:
list[0] = change_char(list[0], -1, 'Z')

Open in new window

0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

837 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question