Python: String replace index

前端 未结 6 1241
面向向阳花
面向向阳花 2020-12-11 05:04

I mean, i want to replace str[9:11] for another string. If I do str.replace(str[9:11], \"###\") It doesn\'t work, because the sequence [9:11] can b

相关标签:
6条回答
  • 2020-12-11 05:07

    Here is a sample code:

    word = "astalavista"
    index = 0
    newword = ""
    addon = "xyz"
    while index < 8:
        newword = newword + word[index]
        index += 1
        ind = index
    
    i = 0
    while i < len(addon):
        newword = newword + addon[i]
        i += 1
    
    while ind < len(word):
        newword = newword + word[ind]
        ind += 1
    
    print newword
    
    0 讨论(0)
  • 2020-12-11 05:10

    Given txt and s - the string you want to replace:

    txt.replace(s, "***", 1).replace(s, "###").replace("***", s)
    

    Another way:

    txt[::-1].replace(s[::-1], "###", 1)[::-1]
    
    0 讨论(0)
  • 2020-12-11 05:11
    str = "cdabcjkewabcef"
    print((str[::-1].replace('cba','###',1))[::-1])
    
    0 讨论(0)
  • 2020-12-11 05:27

    you can do

    s="cdabcjkewabcef"
    snew="".join((s[:9],"###",s[12:]))
    

    which should be faster than joining like snew=s[:9]+"###"+s[12:] on large strings

    0 讨论(0)
  • 2020-12-11 05:28

    You can achieve this by doing:

    yourString = "Hello"
    yourIndexToReplace = 1 #e letter
    newLetter = 'x'
    yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
    
    0 讨论(0)
  • 2020-12-11 05:28

    You can use join() with sub-strings.

    s = 'cdabcjkewabcef'
    sequence = '###'
    indicies = (9,11)
    print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
    >>> 'cdabcjke###cef'
    
    0 讨论(0)
提交回复
热议问题