Replacing instances of a character in a string

前端 未结 13 2376
谎友^
谎友^ 2020-11-22 07:19

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]==\"         


        
13条回答
  •  花落未央
    2020-11-22 07:33

    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.

提交回复
热议问题