[英]How do I replace more than one character in a string Python
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:我应该得到的 output 是:
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.问题来了:如果我输入超过 1 个字符,程序只会传递我输入的最后一个字符,而忽略其他字符。
Here is the output I'm getting:这是我得到的 output:
Enter a string: Welcome to Python
Enter delimiters: oe
Welc me t Pyth n
I will appreciate any help given!我将不胜感激任何帮助! Thanks in advance!!!提前致谢!!!
the parameter string is passed a copy and doesnt change by its self so every time you set x = string.replace(i, " ").参数字符串被传递一个副本并且不会自行更改,因此每次设置 x = string.replace(i, " ") 时。 you are once again getting the original string and replacing only the current character i.您将再次获得原始字符串并仅替换当前字符 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)
You can use re.sub()
for your question:您可以使用re.sub()
来解决您的问题:
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)
Daniel.丹尼尔。 The answer from DSMSTHN is correct but there is an additional note for you. DSMSTHN 的答案是正确的,但还有一个额外的说明。 str doesn't need to be converted into list because it is already iterable. str 不需要转换为 list 因为它已经是可迭代的。 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.