如何替换字符串y Python中不等于字符串x的所有内容?

2024-09-28 13:12:48 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个字符串:

x = "String"
y = "This is a String. Strings are made up of text, not string."

我想用其他内容替换字符串y中不等于字符串x的所有内容,如下所示:

>>> print(y.replace(~x, ""))
StringString

我该怎么做

编辑:修复了一些令人困惑的、不需要的东西


Tags: of字符串text内容stringisnotthis
2条回答

像这样:

  x * y.count(x)

编辑问题之前获取", String, String, "类答案:

def inv_replace(x, y, delim=", "):
  pre = delim if y.index(x) else ""
  post = delim if y.rindex(x) + len(x) != len(y) else ""
  return pre + delim.join([x] * y.count(x)) + post

如果您只是想替换字符串中的单词,只需检查每个单词,如果它不等于要保护的单词,则可以替换它,如下所示:

s = "foo bar foobar bar foocar foo"
sl = s.split(" ") #put all words in a list
for i in range(len(sl)):
  word = sl[i]
  if not word == "bar":
    sl[i] = "newtext" #make the word into "newtext", and replace it in the list
s = sl.join(" ") #put the words back in the string

输出:

>>> "newtext bar newtext bar newtext newtext"

相关问题 更多 >

    热门问题