Solved

Change one character in a string. Easiest way

Posted on 2009-05-05
2
844 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
Comment Utility
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
Comment Utility
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
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 lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

743 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now