Home > Mobile >  How do I replace more than one character in a string Python
How do I replace more than one character in a string Python

Time:11-25

Sorry in advance, I'm barely beginning in programming.

I'm struggling with this program more than I thought I would. Take a look:

string = str(input("Enter a string: "))

delimiter = input("Enter delimiters: ")


s = list(string)

d = list(delimiter)


def split(string, delimiter):

    for i in s:
        if i in d:
            x = string.replace(i, " ")

    print(x)


split(string, delimiter)

And the output I'm supposed to get is:

Enter a string: Welcome to Python

Enter delimiters: oe
W lc m t Pyth n

Here comes the problem: if I enter more than 1 character, the program will only pass the last character I entered and will ignore the others.

Here is the output I'm getting:

 Enter a string: Welcome to Python

 Enter delimiters: oe
 Welc me t  Pyth n

I will appreciate any help given! Thanks in advance!!!

CodePudding user response:

the parameter string is passed a copy and doesnt change by its self so every time you set x = string.replace(i, " "). you are once again getting the original string and replacing only the current character i.

this should do the trick:

def split(string, delimiter):
    x = string
    for i in s:
    if i in d:
        x = string.replace(i, " ")

    print(x)

CodePudding user response:

Daniel. The answer from DSMSTHN is correct but there is an additional note for you. str doesn't need to be converted into list because it is already iterable. So, here is my version of code.

string = input("Enter a string: ")
delimiter = input("Enter delimiters: ")


def split(string, delimiter):
    for s in string:
        if s in delimiter:
            string = string.replace(s, " ")
    print(string)


split(string, delimiter)

CodePudding user response:

You can use re.sub() for your question :

import re

def split(string, delimiter):
    pattern = "["   delimiter   "]"
    new_string = re.sub(pattern, " ", string)
    return new_string

string = str(input("Enter a string: "))
delimiter = input("Enter delimiters: ")

split(string, delimiter)
  • Related