How can I replace a single character in a string in python?
For example: If I have a string abcccc and I want to replace the c at the third position, if I use .replace() it will replace every single c in the string.
How can I replace a single character in a string in python?
For example: If I have a string abcccc and I want to replace the c at the third position, if I use .replace() it will replace every single c in the string.
To set a single character in a string, try something like:
def set_at_string_position(a_string, a_char, position): if position < 0 or len(a_string) <= position: return a_string return a_string[:position] + a_char + a_string[position+1:] print(set_at_string_position('123456789', 'a', -1)) print(set_at_string_position('123456789', 'a', 0)) print(set_at_string_position('123456789', 'a', 3)) print(set_at_string_position('123456789', 'a', 8)) print(set_at_string_position('123456789', 'a', 9)) 123456789 a23456789 123a56789 12345678a 123456789