Replacing instances of a character in a string

前端 未结 13 2692
谎友^
谎友^ 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:59

    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
    

提交回复
热议问题