Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python string.replace() not replacing certain characters

Tags:

python

def replace_at_index(string, index):
    print (string.replace(string[index], "-", 1))

That's my current code for replacing a character with a given index.

  • string "House" with Index 4 produces "Hous-"
  • string "Housee" with Index 5 produces "Hous-e"
  • string "Houseed" with Index 6 produces "Housee-"
  • string "Houseed" with Index 5 produces "Hous-ed"

Not sure why it's doing this. The result I'm wanting is for it to replace the given Index, which in the case of "Housee" Index 5 would be "House-"

like image 955
matt Avatar asked Jul 01 '26 11:07

matt


2 Answers

This is a hack but works:

def replace_at_index(string, index):
   ls = list(string)
   ls[index] = "-"
   s = "".join(ls)
   print(s)
like image 51
ESDAIRIM Avatar answered Jul 04 '26 01:07

ESDAIRIM


Look at the function doc-string: string.replace(old, new, count) so it replaces count as many occurences that it can find.

You cannot change a string. Each string is newly created, it is immutable. What you want is:

def replace_at_index(string, index):
    string = string[:index] + "-" + string[index+1:]
    return string
like image 31
skjerns Avatar answered Jul 04 '26 00:07

skjerns