Replacing instances of a character in a string

Posted on

Solving problem is about exposing yourself to as many situations as possible like Replacing instances of a character in a string and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about Replacing instances of a character in a string, which can be followed any time. Take easy to follow this discuss.

Replacing instances of a character in a string

This simple code that simply tries to replace semicolons (at i-specified postions) by colons does not work:

for i in range(0,len(line)):
     if (line[i]==";" and i in rightindexarray):

It gives the error

TypeError: 'str' object does not support item assignment

How can I work around this to replace the semicolons by colons? Using replace does not work as that function takes no index- there might be some semicolons I do not want to replace.


In the string I might have any number of semicolons, eg “Hei der! ; Hello there ;!;”

I know which ones I want to replace (I have their index in the string). Using replace does not work as I’m not able to use an index with it.

Answer #1:

Strings in python are immutable, so you cannot treat them as a list and assign to indices.

Use .replace() instead:

line = line.replace(';', ':')

If you need to replace only certain semicolons, you’ll need to be more specific. You could use slicing to isolate the section of the string to replace in:

line = line[:10].replace(';', ':') + line[10:]

That’ll replace all semi-colons in the first 10 characters of the string.

Answered By: Martijn Pieters

Answer #2:

You can do the below, to replace any char with a respective char at a given index, if you wish not to use .replace()

word = 'python'
index = 4
char = 'i'
word = word[:index] + char + word[index + 1:]
print word
o/p: pythin
Answered By: Dineshs91

Answer #3:

Turn the string into a list; then you can change the characters individually. Then you can put it back together with .join:

s = 'a;b;c;d'
slist = list(s)
for i, c in enumerate(slist):
    if slist[i] == ';' and 0 <= i <= 3: # only replaces semicolons in the first part of the text
        slist[i] = ':'
s = ''.join(slist)
print s # prints a:b:c;d
Answered By: nneonneo

Answer #4:

If you want to replace a single semicolon:

for i in range(0,len(line)):
 if (line[i]==";"):
     line = line[:i] + ":" + line[i+1:]

Havent tested it though.

Answered By: Vic

Answer #5:

This should cover a slightly more general case, but you should be able to customize it for your purpose

def selectiveReplace(myStr):
    answer = []
    for index,char in enumerate(myStr):
        if char == ';':
            if index%2 == 1: # replace ';' in even indices with ":"
                answer.append("!") # replace ';' in odd indices with "!"
    return ''.join(answer)

Hope this helps

Answered By: inspectorG4dget

Answer #6:

You cannot simply assign value to a character in the string.
Use this method to replace value of a particular character:

name = "India"
result=name .replace("d",'*')

Output: In*ia

Also, if you want to replace say * for all the occurrences of the first character except the first character,
eg. string = babble output = ba**le


name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
return front+back
Answered By: Darshan Jain

Answer #7:

If you are replacing by an index value specified in variable ‘n’, then try the below:

def missing_char(str, n):
 return str
Answered By: Bipin Shetty

Answer #8:

How about this:

sentence = 'After 1500 years of that thinking surpressed'
sentence = sentence.lower()
def removeLetter(text,char):
    result = ''
    for c in text:
        if c != char:
            result += c
    return text.replace(char,'*')
text = removeLetter(sentence,'a')
Answered By: Dylan Maulucci

Leave a Reply

Your email address will not be published. Required fields are marked *