Replacing instances of a character in a string

前端 未结 13 2354
谎友^
谎友^ 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.

    0 讨论(0)
  • 2020-11-22 07:33

    You cannot simply assign value to a character in the string. Use this method to replace value of a particular character:

    name = "India"
    result=name .replace("d",'*')
    

    Output: In*ia

    Also, if you want to replace say * for all the occurrences of the first character except the first character, eg. string = babble output = ba**le

    Code:

    name = "babble"
    front= name [0:1]
    fromSecondCharacter = name [1:]
    back=fromSecondCharacter.replace(front,'*')
    return front+back
    
    0 讨论(0)
  • 2020-11-22 07:34

    To replace a character at a specific index, the function is as follows:

    def replace_char(s , n , c):
        n-=1
        s = s[0:n] + s[n:n+1].replace(s[n] , c) + s[n+1:]
        return s
    

    where s is a string, n is index and c is a character.

    0 讨论(0)
  • 2020-11-22 07:39

    If you are replacing by an index value specified in variable 'n', then try the below:

    def missing_char(str, n):
     str=str.replace(str[n],":")
     return str
    
    0 讨论(0)
  • 2020-11-22 07:39

    You can do this:

    string = "this; is a; sample; ; python code;!;" #your desire string
    result = ""
    for i in range(len(string)):
        s = string[i]
        if (s == ";" and i in [4, 18, 20]): #insert your desire list
            s = ":"
        result = result + s
    print(result)
    
    0 讨论(0)
  • 2020-11-22 07:43

    If you want to replace a single semicolon:

    for i in range(0,len(line)):
     if (line[i]==";"):
         line = line[:i] + ":" + line[i+1:]
    

    Havent tested it though.

    0 讨论(0)
提交回复
热议问题