Solved

Change one character in a string. Easiest way

Posted on 2009-05-05
2
846 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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

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

Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
The really strange introduction Once upon a time there were individuals who intentionally put the grass seeds to the soil with anticipation of solving their nutrition problems. Or they maybe only played with seeds and noticed what happened... Som…
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
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 …

776 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