Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Change one character in a string. Easiest way

Posted on 2009-05-05
2
Medium Priority
?
857 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 1000 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: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering 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

Here I am using Python IDLE(GUI) to write a simple program and save it, so that we can just execute it in future. Because when we write any program and exit from Python then program that we have written will be lost. So for not losing our program we…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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 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…
Suggested Courses

971 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