QBoard » Artificial Intelligence & ML » AI and ML - Python » eplacing instances of a character in a string

eplacing 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==";" and i in rightindexarray): line=":"
    It gives the error
    line=":" 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.
      October 13, 2021 1:47 PM IST
    0
  • 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​
      October 15, 2021 1:54 PM IST
    0
  • 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​
      October 16, 2021 12:52 PM IST
    0
  • 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
      October 16, 2021 2:45 PM IST
    0