Solved

Change one character in a string. Easiest way

Posted on 2009-05-05
2
850 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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: 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

A set of related code is known to be a Module, it helps us to organize our code logically which is much easier for us to understand and use it. Module is an object with arbitrarily named attributes which can be used in binding and referencing. …
The purpose of this article is to demonstrate how we can use conditional statements using Python.
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 modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

628 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