matt
matt

Reputation: 33

Python string.replace() not replacing certain characters

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.

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

Upvotes: 3

Views: 1408

Answers (6)

Pedro oumari
Pedro oumari

Reputation: 1

its replacing you just have to be a little smart about it:

b = '?<\>:/"|'
line='?sqfsq?QSqdqdf/qsdfqsdf\qsdfqs"'
s=""
for char in b:
    print(char)
    # if char in b:
    s=(line.replace(char,''))
    line=s
print(line)
print(s)

Upvotes: 0

Hiram
Hiram

Reputation: 153

The replace method replaces a given substring in a string.

What the code is doing, it's replacing the first occurrence of the character in the string.

What you should do instead is:

def replace_at_index(string, index):
    new_string = string[:index]
    new_string += "-"
    new_string += string[index+1:]
    return new_string

In a pythonic fashion ;)

Upvotes: 1

wjandrea
wjandrea

Reputation: 33107

It's replacing the first occurrence of the character you asked it to replace. If there are duplicate characters, it won't necessarily be at the same index that you got the character from.

-- comment by Barmar

What you could do instead is slice the string at the index, then join it on the replacement.

def replace_at_index(string, index):
    parts = string[:index], string[index+1:]
    return "-".join(parts)


for s, i in ("House", 4), ("Housee", 5), ("Houseed", 6), ("Housee", 5):
    print(replace_at_index(s, i))

Output:

Hous-
House-
Housee-
House-

Although you might want to add a check to make sure that index is in range.

Upvotes: 0

trozzel
trozzel

Reputation: 638

str.replace is not replacing the index, but the first occurrence of a value. Since "Housee"[5] == 'e', it will replace the first 'e'

def replace_at_index(string, index):
    newstr = string[:index] + '-' + string[index+1:]
    return newstr

Upvotes: 1

ESDAIRIM
ESDAIRIM

Reputation: 661

This is a hack but works:

def replace_at_index(string, index):
   ls = list(string)
   ls[index] = "-"
   s = "".join(ls)
   print(s)

Upvotes: 3

skjerns
skjerns

Reputation: 2188

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

Upvotes: 2

Related Questions