【问题标题】:String.replace(x,x,count => 1) in PythonPython 中的 String.replace(x,x,count => 1)
【发布时间】:2020-02-18 07:04:53
【问题描述】:

我是 python 新手,正在学习它。在我的项目代码中,我在替换函数中看到计数以这种格式给出。当我在 Python 编辑器中运行时,它会出现此错误。

"Bharath..Bharath..Bharath".replace("..", ".", count => 1)
SyntaxError: invalid syntax

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.7/py_compile.py", line 147, in compile
    raise py_exc
py_compile.PyCompileError:   File "./prog.py", line 1

    x="Bharath..Bharath..Bharath".replace("..", ".", count => 1)

                                                            ^
SyntaxError: invalid syntax

谁能告诉我这个计数 => 1 意味着我知道最后一个参数是要替换的出现次数。

谢谢

【问题讨论】:

  • 试试 count=1 或 1。“..”.replace(“..”,”.”,1)

标签: python replace syntax


【解决方案1】:

在 Python 中,这可以很容易地完成String.replace(StringToReplace, ReplaceWith, Count)

你的例子

x="Bharath..Bharath..Bharath".replace("..", ".", 1)应该可以工作。像“count”这样的关键字在这里不起作用。

所以你已经接近解决方案了。 :)

【讨论】:

    【解决方案2】:

    替换方法不接受关键字参数,所以只需使用以下代码更新您的代码。

    "Bharath..Bharath..Bharath".replace("..", ".", 1)
    

    【讨论】:

      猜你喜欢
      • 2019-08-02
      • 2016-02-03
      • 2012-10-06
      • 2017-01-19
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多