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

Recommended Answers

All 2 Replies

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!

Thank you so much this helped a lot!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.