【问题标题】:Python replace word with "word"Python用“单词”替换单词
【发布时间】:2020-03-27 21:27:12
【问题描述】:

如何在python中用“word”替换word? 我已经试过了:

str = "some_word"
str.replace("some_word", '"some_word"')

但这不起作用

【问题讨论】:

  • 你想做什么?这个是来做什么的?另外,不要将变量命名为 str
  • 它确实有效。但请记住,replace 方法不能就地工作。而是做str = str.replace("some_word", '"some_word"')
  • 另外,尝试检查单引号和双引号之间的区别:tutorialspoint.com/…

标签: python string replace quotes


【解决方案1】:

1) 不要使用 str 作为变量名,因为它是 python 中的关键字。

d = 'ab'
print(d.replace('ab','ac'))

2) 字符串在 python 中是不可变的,所以你必须像这样重新分配它:

d = d.replace('ab','ac')
print(d)

【讨论】:

    【解决方案2】:

    您应该创建一个变量来接收替换的值。

     str = "some_word"
     str = replace(old_chars, new_chars)
    

    【讨论】:

      【解决方案3】:
      >>> strr = "some_word"
      >>> strr = f'"{strr}"'
      >>> print(strr)
      "some_word"
      
      

      【讨论】:

      • 如果用户不需要替换整个字符串,而只替换其中的一部分怎么办?这是行不通的,从我的角度来看,解决方案太具体了。此外,它仅适用于新版本的 Python
      【解决方案4】:

      这非常有效:

      a = "some_word"
      print(a) # some_word
      a = a.replace("some_word", '"some_word"')
      print(a) # "some_word"
      

      如果您想将 整个 字符串用双引号括起来,而不仅仅是其中的一部分,您可以使用以下方法之一:

      a = "some_word"
      a1 = '"{}"'.format(a)
      a2 = '"' + a + '"'
      a3 = f'"{a}"'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        • 2021-12-29
        • 2015-03-02
        • 1970-01-01
        相关资源
        最近更新 更多