【问题标题】:How do you search for and delete a phrase from a string in Python? [duplicate]如何在 Python 中从字符串中搜索和删除短语? [复制]
【发布时间】:2018-01-22 18:40:29
【问题描述】:

我是python新手,所以这个问题可能有一个简单的答案,但我看了看,一无所获。

我想定义一个函数,当它被输入时:“function(abcdefg123, fg1, " ")” 返回是这样的:“abcde 23”。我想应该是这样的:

def function(something, what_to_deleat, what_to_substitute):
  if str(what_to_deleat) in str(something):
    return ## Code that replaces "what_to_deleat" with "what_to_substitute"  within "something"
  else:
    return something

如果输入了 'function("25.0", ".0", "")',实际应用程序(以及我想要使用的应用程序)会将 25.0 转换为 25。

【问题讨论】:

标签: python


【解决方案1】:

我想最简单的解决方案是

 def function(something, what_to_delete, what_to_substitute):
    return something.replace(what_to_delete, what_to_substitute)

当然,您根本不需要在这里编写自己的函数...

https://docs.python.org/2/library/string.html#string.replace

【讨论】:

  • 谢谢...那为什么这不起作用?
  • def cut(n): if str(n) == str(n).replace(".0", ""): return str(n).replace(".0", "") 否则:返回 str(n)
  • 我尝试了很多东西,但它要么给出错误,要么什么都不做。例如cut(25.0) 只给出 25.0,而不是我想要的 25。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 2013-06-16
  • 2014-01-26
相关资源
最近更新 更多