Replacing instances of a character in a string

Question:

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):
         line[i]=":"

It gives the error

line[i]=":"
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.

Example

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.

Asked By: The Unfun Cat

||

Answers:

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

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

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(":")
            else:
                answer.append("!") # replace ';' in odd indices with "!"
        else:
            answer.append(char)
    return ''.join(answer)
Answered By: inspectorG4dget

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

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

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

def missing_char(str, n):
 str=str.replace(str[n],":")
 return str
Answered By: Bipin Shetty

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

Code:

name = "babble"
front= name [0:1]
fromSecondCharacter = name [1:]
back=fromSecondCharacter.replace(front,'*')
return front+back
Answered By: Darshan Jain

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

To replace a character at a specific index, the function is as follows:

def replace_char(s , n , c):
    n-=1
    s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
    return s

where s is a string, n is index and c is a character.

Answered By: Sanket Hire

I wrote this method to replace characters or replace strings at a specific instance. instances start at 0 (this can easily be changed to 1 if you change the optional inst argument to 1, and test_instance variable to 1.

def replace_instance(some_word, str_to_replace, new_str='', inst=0):
    return_word = ''
    char_index, test_instance = 0, 0
    while char_index < len(some_word):
        test_str = some_word[char_index: char_index + len(str_to_replace)]
        if test_str == str_to_replace:
            if test_instance == inst:
                return_word = some_word[:char_index] + new_str + some_word[char_index + len(str_to_replace):]
                break
            else:
                test_instance += 1
        char_index += 1
    return return_word
Answered By: Matt Farguson

to use the .replace() method effectively on string without creating a separate list
for example take a look at the list username containing string with some white space, we want to replace the white space with an underscore in each of the username string.

names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]
usernames = []

to replace the white spaces in each username consider using the range function in python.

for name in names:
    usernames.append(name.lower().replace(' ', '_'))

print(usernames)

Or if you want to use one list:

for user in range(len(names)):
   names[user] = names[user].lower().replace(' ', '_')

print(names)
Answered By: N.Samuel

You can do this:

string = "this; is a; sample; ; python code;!;" #your desire string
result = ""
for i in range(len(string)):
    s = string[i]
    if (s == ";" and i in [4, 18, 20]): #insert your desire list
        s = ":"
    result = result + s
print(result)
Answered By: shabgard tanha
names = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

usernames = []

for i in names:
    if " " in i:
        i = i.replace(" ", "_")
    print(i)

Output:
Joey_Tribbiani
Monica_Geller
Chandler_Bing
Phoebe_Buffay

Answered By: Kasem777

My problem was that I had a list of numbers, and I only want to replace a part of that number, soy I do this:

original_list = ['08113', '09106', '19066', '17056', '17063', '17053']

# With this part I achieve my goal
cves_mod = []
for i in range(0,len(res_list)):
    cves_mod.append(res_list[i].replace(res_list[i][2:], '999'))
cves_mod

# Result
cves_mod
['08999', '09999', '19999', '17999', '17999', '17999']
Answered By: Joselin Ceron

Even more simpler:

input = "a:b:c:d"
output =''
for c in input:
    if c==':':
        output +='/'
    else:
        output+=c
print(output)

output: a/b/c/d

Answered By: jorgems

i tried using this instead as a 2 in 1

usernames = ["Joey Tribbiani", "Monica Geller", "Chandler Bing", "Phoebe Buffay"]

# write your for loop here
for user in range(0,len(usernames)):
    usernames[user] = usernames[user].lower().replace(' ', '_')

print(usernames)
Answered By: Vern

Cleaner way to replace character at a specific index

def replace_char(str , index , c):
    return str[:index]+c+str[index+1:]
Answered By: Alberto Perez
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.