Replacing instances of a character in a string

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

    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
    

提交回复
热议问题