2

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.

1
  • replace has a occurance parameter with that you can control how many times it will replace. If you google it you will find it Commented Feb 16, 2018 at 6:26

1 Answer 1

3

To set a single character in a string, try something like:

Code:

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:] 

Test Code:

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)) 

Result:

123456789 a23456789 123a56789 12345678a 123456789 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.