0

I need to change a character inside of a string in a list
ex
horizontal=2
across=2
List=['abcdefg',
'hijklmno',
'pqrstuv',]
I would want to change just one character like
the third character in the third string(but I don't know that the program will know using horizontal and across) to 'd'.

if you have further questions please ask

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by flip121
0

Well for starters, your List construction will cause an error as there is a comma after the 3rd string, which is the last index so it shouldn't have the comma after it.

Here's an example I think will help:

mylist = [
	'abcdefg',
	'hijklmno',
	'pqrstuv'
]
listindex = 2
charindex = 2

temp = mylist[listindex]
mylist[listindex] = temp[:charindex] + 'd' + temp[charindex + 1:]

Which changes the "r" in the third string in the list to a "d".
It's simple slicing: current string up to (but not including) the character's index, plus the new character, plus everything after the character's index. Then it reassigns that to the list's index.

It may look fine to update "temp" with the newly sliced string, but "temp" is only a copy of the original list index I made to make the slicing expression look cleaner. You have to actually modify the list's index for the change to be assigned back in.

Hope that helped!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.